Python List Comprehensions
List Satellite
List Comprehensions
Transform loops into concise expressions without sacrificing readability.
Syntax
numbers = [n for n in range(10)]
even_squares = [n * n for n in range(10) if n % 2 == 0]
matrix = [[col for col in row] for row in grid]
- Format:
[expression for item in iterable if condition]. - Nest comprehensions carefully; readability matters.
Best practices
- Keep comprehensions single-purpose. If you need multiple statements, use a loop.
- Use generator expressions
(expression for ...)when you only need iteration, not a full list. - Pair with functions like
sum,any,allfor quick aggregations.