📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials Python from Zero List Comprehensions

List Comprehensions

5 min read
List comprehensions create lists concisely: [x*2 for x in range(10)]. Add a filter condition: [x for x in data if x > 0]. Dict and set comprehensions work the same way. Generator expressions use () and are lazy.

List Comprehensions

# Basic
squares = [x**2 for x in range(10)]

# With condition
evens = [x for x in range(20) if x % 2 == 0]

# Nested
matrix = [[i*j for j in range(1,4)] for i in range(1,4)]

# Dict comprehension
lengths = {word: len(word) for word in ['hello','world']}

# Set comprehension
unique_lens = {len(w) for w in ['hi','bye','hello']}