logo

List Comprehensions

List comprehensions are Python's alternative to map() and filter(). Many Python developers prefer them for readability.

# map equivalent
numbers = [1, 2, 3, 4, 5]
squared = [x ** 2 for x in numbers]

Add a condition to filter:

# filter + map equivalent
evens_squared = [x ** 2 for x in numbers if x % 2 == 0]

The syntax is: [expression for item in sequence if condition]. The condition is optional.

Comprehensions also work for dictionaries and sets:

# Dictionary comprehension
squares = {x: x ** 2 for x in range(5)}

# Set comprehension
unique_lengths = {len(word) for word in words}

Comprehensions are often clearer than map()/filter() with lambdas. They're a core Python idiom.

I cover comprehension patterns in my Functional Programming course.