Lists
List Comprehensions
Creating lists with comprehension syntax
Interview: Signature Pythonic pattern — interviewers expect fluency with comprehensions
List comprehensions provide a concise, readable, and often faster way to create lists. They replace the common pattern of creating an empty list, looping, and appending. The syntax is [expression for item in iterable if condition].
Basic Syntax
- Transform:
[x**2 for x in range(10)]— apply expression to each element - Filter:
[x for x in data if x > 0]— keep elements that pass condition - Transform + Filter:
[x**2 for x in data if x > 0]— both in one expression - Conditional expression:
["even" if x%2==0 else "odd" for x in range(5)]
Advanced Patterns
- Nested loops:
[x for row in matrix for x in row]— flatten 2D list - Nested comprehensions:
[[i*j for j in range(3)] for i in range(3)]— create 2D list - Multiple conditions:
[x for x in range(100) if x%2==0 if x%3==0]— AND logic - With zip:
[a+b for a, b in zip(list1, list2)]— parallel iteration - Dict/set comprehensions:
{k: v for k, v in pairs}and{x for x in data if x > 0}
Performance Considerations
- Comprehensions are typically faster than equivalent for loops because the iteration is optimized in C
- For large datasets, use generator expressions
(x**2 for x in range(10**6))to avoid creating the full list in memory - Don't nest more than 2 levels of loops — readability degrades rapidly
- If the comprehension is complex, extract it into a named function for clarity
Best Practice
Use comprehensions for simple transformations. If you need more than 2 for/if clauses, or if the expression is complex, use a regular for loop with append. Readability always wins over cleverness.
Use Cases
Data transformation and filtering in data pipelines
Creating derived collections from existing data
Building matrices and grids for algorithms
Replacing map/filter with more readable syntax
Common Mistakes
Writing overly complex comprehensions (>2 for/if clauses) that hurt readability
Confusing nested loop order: [x for row in matrix for x in row] reads left-to-right as nested for loops
Using list comprehension when a generator expression would be more memory-efficient
Not knowing that comprehensions create a new scope for the loop variable (it leaks in Python 2)