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.
Figure 34.1: Anatomy of a list comprehension: Output Expression < Iteration Loop < Conditional Filter.
# 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]
{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}
{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'}
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]
[] 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.