Pythonic Patterns

Difficulty: Advanced

Writing Pythonic code means using the language's features idiomatically rather than translating patterns from other languages. Interviewers look for this because it signals fluency and practical experience with Python.

List comprehensions are one of the most distinctive Python features. They replace verbose for-loops-with-append patterns into concise, readable one-liners: `[x2 for x in range(10) if x % 2 == 0]`. Dict and set comprehensions follow the same pattern. Comprehensions are generally faster than equivalent loops because they are optimized at the bytecode level.

The built-in functions `enumerate()` and `zip()` are indispensable. `enumerate()` gives you index-value pairs without maintaining a manual counter. `zip()` iterates over multiple sequences in parallel, stopping at the shortest. Combined with unpacking, they produce clean, readable iteration patterns.

Unpacking is used everywhere in Python: multiple assignment (`a, b = 1, 2`), swapping (`a, b = b, a`), starred expressions (`first, *rest = items`), and function argument unpacking (`func(*args, kwargs)`). Understanding unpacking is essential for writing concise code.

The walrus operator (`:=`), introduced in Python 3.8, allows assignment within expressions. It is useful in while-loops, list comprehensions, and conditional expressions where you want to both compute and test a value. The ternary expression `x if condition else y` replaces verbose if-else blocks for simple conditional assignments.

These patterns are not just stylistic preferences -- they make code shorter, more readable, and often faster. Interviewers expect you to use them naturally when solving problems.

Code examples

List comprehension with filtering

# Squares of even numbers from 0 to 9
squares = [x2 for x in range(10) if x % 2 == 0]
print("squares:", squares)

# Dict comprehension
word_lengths = {w: len(w) for w in ["python", "is", "great"]}
print("lengths:", word_lengths)

Comprehensions replace multi-line loops with concise expressions. The filter condition (if x % 2 == 0) is optional.

enumerate and zip

fruits = ["apple", "banana", "cherry"]
for i, fruit in enumerate(fruits, start=1):
    print(f"{i}. {fruit}")

names = ["Alice", "Bob", "Charlie"]
scores = [95, 87, 92]
for name, score in zip(names, scores):
    print(f"{name}: {score}")

enumerate provides index-value pairs. zip combines multiple iterables element-wise. Both use unpacking in the for loop.

Unpacking patterns

# Multiple assignment and swap
a, b = 1, 2
a, b = b, a
print(f"swapped: a={a}, b={b}")

# Starred unpacking
first, *middle, last = [1, 2, 3, 4, 5]
print(f"first={first}, middle={middle}, last={last}")

# Nested unpacking
pairs = [(1, "a"), (2, "b"), (3, "c")]
for num, letter in pairs:
    print(f"{num}->{letter}", end=" ")
print()

Python's unpacking works with any iterable. Starred expressions capture remaining elements into a list.

Walrus operator and ternary

# Walrus operator: assign and test in one expression
data = [1, 5, 3, 8, 2, 7]
result = [y for x in data if (y := x * 2) > 6]
print("filtered doubled:", result)

# Ternary expression
age = 20
status = "adult" if age >= 18 else "minor"
print(f"age {age}: {status}")

The walrus operator (:=) assigns x*2 to y and filters by y > 6 in a single comprehension. Ternary provides inline conditional assignment.

Key points

Concepts covered

list comprehension, enumerate, zip, unpacking, walrus operator, ternary