Python Comprehensions: List, Dictionary & Set Comprehensions Masterclass

One of Python's most celebrated and elegant features is comprehensions. Comprehensions offer a compact, declarative syntax to construct new lists, dictionaries, and sets from existing iterables in a single line of code, replacing boilerplate multi-line for loops and .append() calls.

Python List Comprehension Syntax Anatomy Diagram

Figure 34.1: Anatomy of a list comprehension: Output Expression < Iteration Loop < Conditional Filter.


1. List Comprehensions: Syntax & Comparison

# Task: Get squares of even numbers from 1 to 10

# Traditional for loop:
even_squares = []
for x in range(1, 11):
    if x % 2 == 0:
        even_squares.append(x ** 2)

# Pythonic List Comprehension:
even_squares_comp = [x ** 2 for x in range(1, 11) if x % 2 == 0]

print("Loop result:         ", even_squares)       # [4, 16, 36, 64, 100]
print("Comprehension result:", even_squares_comp)  # [4, 16, 36, 64, 100]

2. Dictionary Comprehensions ({k: v for ...})

Construct dictionaries dynamically from sequences:

# Create a student score lookup dictionary:
names = ["Aman", "Rhea", "Vikram", "Pooja"]
marks = [85, 92, 78, 95]

# Zip into dictionary with comprehension:
student_scores = {name: mark for name, mark in zip(names, marks) if mark >= 80}
print("Honors Students:", student_scores)
# {'Aman': 85, 'Rhea': 92, 'Pooja': 95}

3. Set Comprehensions ({x for ...})

Extract unique, deduplicated elements in one step:

text = "veewom python programming masterclass"
# Extract unique vowels:
unique_vowels = {char for char in text if char in "aeiou"}
print("Unique Vowels in Text:", unique_vowels)  # {'a', 'e', 'i', 'o'}

4. Flattening a 2D Matrix (Nested Comprehensions)

matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

# Flatten 2D grid into a 1D list:
flattened = [val for row in matrix for val in row]
print("Flattened List:", flattened)
# [1, 2, 3, 4, 5, 6, 7, 8, 9]

Frequently Asked Questions (FAQ)

What is the difference between [x for x in iterable] and (x for x in iterable)?

Square brackets [] create an in-memory list comprehension that evaluates immediately. Parentheses () create a lazy generator expression that yields items one by one on demand, saving massive memory on large datasets.
Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!