Page18/20
Comprehensions & Generators Β· Page 1 of 2
List & Dictionary Comprehensions
Comprehensions & Generators
List Comprehensions
List comprehensions provide a concise way to create lists. They're readable AND fast.
Basic Syntax
# Traditional approach
squares = []
for x in range(5):
squares.append(x**2)
# Comprehension (cleaner!)
squares = [x**2 for x in range(5)] # [0, 1, 4, 9, 16]
With Conditionals
# Keep only even numbers
evens = [x for x in range(10) if x % 2 == 0]
# [0, 2, 4, 6, 8]
# Transform AND filter
high_scores = [s*1.1 for s in scores if s >= 80]
Nested Comprehensions
# Flatten a 2D matrix
matrix = [[1, 2, 3], [4, 5, 6]]
flattened = [num for row in matrix for num in row]
# [1, 2, 3, 4, 5, 6]
Dictionary & Set Comprehensions
Similar to lists, but for dictionaries and sets:
# Dict comprehension
scores_dict = {name: score for name, score in zip(names, scores)}
# Set comprehension (removes duplicates)
unique_lengths = {len(word) for word in words}
Pro tip: Comprehensions are faster and more Pythonic than loops with append().
main.py
Loading...
OUTPUT
βΆClick "Run Code" to executeβ¦