← Back to Python Course | Chapter 14: Advanced Python & Tools | Lesson 10 of 15

Python Comprehensions Advanced

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

python
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

python
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

python
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

python
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

python
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))

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.