Comprehensions
A comprehension builds a new collection from an old one in a single readable line. Compare the long way with the short way:
# long way
squares = []
for n in range(5):
squares.append(n * n)
# list comprehension
squares = [n * n for n in range(5)]
print(squares) # [0, 1, 4, 9, 16]Add an if at the end to keep only some items:
evens = [n for n in range(10) if n % 2 == 0]
print(evens) # [0, 2, 4, 6, 8]A dict comprehension uses key: value inside braces:
squared = {n: n * n for n in range(4)}
print(squared) # {0: 0, 1: 1, 2: 4, 3: 9}A set comprehension looks the same but builds a set of unique values:
lengths = {len(w) for w in ["hi", "yo", "hey"]}
print(lengths) # {2, 3}Swap the brackets for parentheses and you get a generator expression: it produces values lazily, one at a time, which is perfect to feed straight into sum() without building a list:
total = sum(n * n for n in range(5)) # 30Use a list comprehension to build evens containing the even numbers from 0 to 9. Use a dict comprehension to build cubes mapping each n in range(4) to n ** 3. Finally, use sum() with a generator expression to store the total of n * 2 for n in range(5) in doubled_total.
This lesson is locked
Lessons open one at a time. Finish the previous lesson to unlock this one.