Python Comprehensions
Comprehensions provide a concise way to create lists, sets, dictionaries from existing iterables using a single line of code.
💻 List Comprehensions
# Basic syntax: [expression for item in iterable]
squares = [x**2 for x in range(10)]
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# With condition
evens = [x for x in range(20) if x % 2 == 0]
# [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
# Nested comprehension
matrix = [[i*j for j in range(3)] for i in range(3)]
# [[0, 0, 0], [0, 1, 2], [0, 2, 4]]
# String manipulation
words = ["hello", "world"]
uppercase = [word.upper() for word in words]
# ['HELLO', 'WORLD']🔧 Dict & Set Comprehensions
# Dictionary comprehension
squares_dict = {x: x**2 for x in range(5)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
# From two lists
keys = ['a', 'b', 'c']
values = [1, 2, 3]
combined = {k: v for k, v in zip(keys, values)}
# {'a': 1, 'b': 2, 'c': 3}
# Set comprehension (unique values)
unique_lengths = {len(word) for word in ["hello", "hi", "hey"]}
# {2, 3, 5}🎯 Key Takeaways
- List comprehension: [expr for item in iterable]
- Condition: [expr for item in iterable if condition]
- Dict comprehension: {k: v for item in iterable}
- Set comprehension: {expr for item in iterable}
- Nested: Multiple for clauses
- Performance: Faster than loops