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

Python Comprehensions Advanced

Advanced comprehensions build lists, sets, and dictionaries in one line, even with loops inside loops. It is like a compact recipe that makes a whole batch at once.
Syntax
python
[expression for item in iterable if condition]
[expression for outer in iter1 for inner in iter2]
{expression for item in iterable}

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]  # nested loop plus a filter, all in one expression
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}  # builds key-value pairs in one expression
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}  # {} with no colon means a set, duplicates dropped automatically
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)]  # builds the whole list in memory immediately
squares_gen = (x * x for x in range(5))  # parentheses make this a lazy generator instead
print(squares_list)
print(list(squares_gen))  # values are only computed when consumed
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Making comprehensions so nested that nobody can read them, when a for loop would be clearer.
  2. Using a list comprehension where a generator expression ( ... ) would avoid storing a huge list.
  3. Expecting a set comprehension to work as a dictionary one: {x for x in items} builds a set, while {k: v for ...} with a colon builds a dictionary.

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.