Python Comprehensions Advanced
In this page:
Advanced List Comprehensions
A single list comprehension can combine multiple for clauses (for nested loops) and multiple if clauses (for compound conditions) in one expression, replacing what would otherwise be several lines of nested loops and conditionals with a more compact, single-line equivalent.
Example: Advanced List Comprehensions
matrix = [[1, 2], [3, 4]]
result = [x for row in matrix for x in row if x % 2 == 0]
print(result)
Dictionary Comprehensions
Dictionary comprehensions use the same for/if structure as list comprehensions but build key-value pairs with {key_expr: value_expr for ...} syntax, letting you construct a dictionary dynamically from an existing iterable in one expression instead of looping and assigning keys manually.
Example: Dictionary Comprehensions
nums = [1, 2, 3]
squares = {n: n * n for n in nums}
print(squares)
Set Comprehensions
Set comprehensions use {expr for ...} syntax (no colon, distinguishing them from dict comprehensions) and automatically discard duplicate results, since sets by definition only hold unique elements -- useful whenever you need distinct values derived from a larger dataset.
Example: Set Comprehensions
nums = [1, 2, 2, 3, 3]
unique_squares = {n * n for n in nums}
print(unique_squares)
Nested Comprehensions
Nesting one comprehension inside another, such as a list comprehension building each row of a list comprehension building rows, lets you generate 2D structures like matrices or grids in a single compact expression, though readability suffers quickly once nesting goes more than two levels deep.
Example: Nested Comprehensions
matrix = [[row * 3 + col for col in range(3)] for row in range(2)]
print(matrix)
Memory and Generator Expressions
All comprehensions build their entire result in memory at once, which becomes wasteful for very large datasets you only intend to iterate over once. Swapping square brackets for parentheses turns a list comprehension into a generator expression, which computes and yields values lazily one at a time instead of holding the whole collection in memory.
Example: Memory and Generator Expressions
squares_list = [x * x for x in range(5)]
squares_gen = (x * x for x in range(5))
print(squares_list)
print(list(squares_gen))
Chapter Quiz — Complete all 15 topics to unlock
0/15 topics done
Complete these topics first:
- Python PEP 8 Style Guide
- Python Debugging Techniques
- Python Testing with unittest
- Python Common Mistakes
- Python Interview Questions
- Python map() & filter()
- Python reduce()
- Python zip() & enumerate()
- Python sorted() & key Functions
- Python Comprehensions Advanced
- Python Turtle Graphics
- Python tkinter Introduction
- Python tkinter Widgets
- Python pygame Introduction
- Python Mini Projects