Pythonic idioms
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.
Looping
# 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
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
# 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
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 namesDictionaries
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
f"{name} is {age}" # not "…" + str(age)
", ".join(names) # not a loop with +=
text.startswith(("http://", "https://")) # several prefixes at onceBuilding a long string with += in a loop creates a new string every time; collect parts in a list and join once.
Resources: with
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:
try:
value = int(text)
except ValueError:
value = 0It’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:
while (line := input("> ")) != "quit":
print("You typed", line)and to avoid computing something twice:
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_casefor functions and variables,CapWordsfor classes,UPPER_CASEfor 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:
uvx ruff format . # reformat code automatically (black-compatible)
uvx ruff check . # find bugs, unused imports and non-idiomatic codeMost 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.
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.
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")names = ["Asha", "Ben", "Chen", "Dee"]
scores = [91, 0, 85, 62]
colours = {"Asha": "red", "Chen": "blue"}
for position, (name, score) in enumerate(zip(names, scores), start=1):
print(f"{position}. {name}: {score}")
print([name for name, score in zip(names, scores) if score >= 50])
print(f"Average: {round(sum(scores) / len(scores), 1)}")
best_name, _ = max(zip(names, scores), key=lambda pair: pair[1])
print(f"Best: {best_name}")
for name in names:
if colours.get(name, "grey") in ("red", "blue"):
print(f"{name} has a primary colour")
if any(score == 0 for score in scores):
print("Someone scored zero")
if names:
print(f"We have {len(names)} students")Summary
- Loop over items directly; use
enumeratefor positions andzipfor parallel lists — almost neverrange(len(...)). - Rely on truthiness (
if items:),inwith 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
withfor resources,dict.get/setdefaultfor defaults, and EAFP (try/except) where checking first is unreliable. - Follow PEP 8 and let a formatter and linter (ruff, black) handle style automatically.