Pythonic idioms

Topic 2 of 2 in Pythonic Python7 min readBeginnerFree course

Overview

Code can be correct and still feel foreign. Pythonic code uses the language’s own features the way they were designed to be used: it’s shorter, clearer, and usually faster. Most of these idioms have appeared earlier in the course; this lesson collects them, so you can recognise and apply them everywhere.

Pythonic idioms: clunky but working code on the left, Pythonic code on the right. for i in range(len(names)): print(i, names[i]) becomes for i, name in enumerate(names): print(i, name). for i in range(len(a)): print(a[i], b[i]) becomes for x, y in zip(a, b): print(x, y). if x == 1 or x == 2 or x == 3: becomes if x in (1, 2, 3):. if len(items) == 0: becomes if not items:.

Looping

Python
# Not Pythonic                          # Pythonic
for i in range(len(names)):             for name in names:
    print(names[i])                         print(name)

for i in range(len(names)):             for i, name in enumerate(names):
    print(i, names[i])                      print(i, name)

for i in range(len(names)):             for name, score in zip(names, scores):
    print(names[i], scores[i])              print(name, score)

for i in range(len(items) - 1, -1, -1): for item in reversed(items):
    print(items[i])                         print(item)

Loop over a dictionary’s pairs with .items(), and over sorted data with sorted(...) rather than sorting a copy first.

Conditions

Python
if len(items) == 0:          →   if not items:
if name != "":               →   if name:
if flag == True:             →   if flag:
if x == None:                →   if x is None:
if x == 1 or x == 2:         →   if x in (1, 2):
if 0 < x and x < 10:         →   if 0 < x < 10:

Careful with truthiness when 0 or "" are valid values: if count: is False for a count of 0. When you mean “is there a value at all?”, write if count is not None:.

Building and summarising collections

Python
# Build a list
result = []                              result = [x * 2 for x in items if x > 0]
for x in items:
    if x > 0:
        result.append(x * 2)

# Summarise
total = sum(prices)
largest = max(scores)
best = max(students, key=lambda s: s.score)
found = any(word in text for word in banned)
valid = all(len(pw) >= 12 for pw in passwords)
counts = Counter(words)

Assignment and unpacking

Python
a, b = b, a                              # swap
first, *rest = items                     # split off the first item
name, age = get_user()                   # multiple return values
for key, value in settings.items():      # unpack in loops
x = y = 0                                # same value to several names

Dictionaries

Python
colour = colours.get(name, "grey")       # default for missing keys
groups.setdefault(team, []).append(name) # or collections.defaultdict(list)
merged = defaults | overrides            # merge two dicts (later wins)

Strings

Python
f"{name} is {age}"                       # not "…" + str(age)
", ".join(names)                         # not a loop with +=
text.startswith(("http://", "https://")) # several prefixes at once

Building a long string with += in a loop creates a new string every time; collect parts in a list and join once.

Resources: with

Python
with open(path, encoding="utf-8") as f:  # closed automatically
    data = f.read()

The same pattern appears for locks, network connections and database transactions: a context manager sets something up and guarantees it’s cleaned up.

EAFP: Easier to Ask Forgiveness than Permission

Python style often tries the operation and handles the failure, rather than checking every condition first:

Python
try:
    value = int(text)
except ValueError:
    value = 0

It’s especially right when checking first could be wrong by the time you act (does the file exist? — it might be deleted a millisecond later). For simple dictionary lookups, get() is better than either style.

The walrus operator :=

:= assigns and returns a value inside an expression. It’s handy in loops that read until there’s nothing left:

Python
while (line := input("> ")) != "quit":
    print("You typed", line)

and to avoid computing something twice:

Python
if (n := len(items)) > 10:
    print(f"Too many items: {n}")

Use it sparingly — it’s easy to overdo.

Style: PEP 8 and tools

PEP 8 is Python’s official style guide. The essentials:

  • 4 spaces per indent; lines under about 80–100 characters;
  • snake_case for functions and variables, CapWords for classes, UPPER_CASE for constants;
  • spaces around operators (x = a + b) and after commas, none inside brackets;
  • two blank lines between top-level functions and classes;
  • imports at the top, one per line, standard library first.

You don’t need to memorise it. Let tools do it:

Terminal
uvx ruff format .        # reformat code automatically (black-compatible)
uvx ruff check .         # find bugs, unused imports and non-idiomatic code

Most editors can run a formatter every time you save.

The Zen of Python

Type import this in the REPL to see Python’s guiding principles. A few that sum up this lesson: Beautiful is better than ugly. Simple is better than complex. Readability counts. There should be one — and preferably only one — obvious way to do it.

The test for Pythonic code: could a Python programmer read it aloud and understand it at once? If you’re managing indexes by hand, there’s probably a better way.

Exercise

Refactor to Pythonic code

The starter code works, but it’s written like another language. Rewrite it using the idioms from this lesson — enumerate, zip, truthiness, in with a tuple, dict.get, a comprehension, sum/max with a generator or key, any, and an f-string — so that it is shorter and clearer but prints exactly the same output.

Python
names = ["Asha", "Ben", "Chen", "Dee"]
scores = [91, 0, 85, 62]
colours = {"Asha": "red", "Chen": "blue"}

i = 0
while i < len(names):
    print(str(i + 1) + ". " + names[i] + ": " + str(scores[i]))
    i = i + 1

passed = []
for i in range(len(scores)):
    if scores[i] >= 50:
        passed.append(names[i])
print(passed)

total = 0
for s in scores:
    total = total + s
print("Average: " + str(round(total / len(scores), 1)))

best_index = 0
for i in range(len(scores)):
    if scores[i] > scores[best_index]:
        best_index = i
print("Best: " + names[best_index])

for name in names:
    if name in colours:
        colour = colours[name]
    else:
        colour = "grey"
    if colour == "red" or colour == "blue":
        print(name + " has a primary colour")

has_zero = False
for s in scores:
    if s == 0:
        has_zero = True
if has_zero == True:
    print("Someone scored zero")

if len(names) > 0:
    print("We have " + str(len(names)) + " students")

Summary

  • Loop over items directly; use enumerate for positions and zip for parallel lists — almost never range(len(...)).
  • Rely on truthiness (if items:), in with a tuple, x is None, and unpacking for swaps and multiple returns.
  • Use comprehensions and built-ins (sum, max, any, all, sorted) instead of hand-written loops for common patterns.
  • Use with for resources, dict.get/setdefault for defaults, and EAFP (try/except) where checking first is unreliable.
  • Follow PEP 8 and let a formatter and linter (ruff, black) handle style automatically.