Comprehensions and generators
Transform collections in one expression and stream values lazily.
What you will be able to do
- Write list, dict and set comprehensions
- Filter during a comprehension
- Use generator expressions to save memory
Comprehensions replace a loop that builds a new collection. Generator expressions use the same syntax with parentheses and yield values one at a time.
scores = {"html": 88, "css": 72, "js": 91}
passed = [name for name, score in scores.items() if score >= 80]
print(passed)
squares = {n: n * n for n in range(1, 6)}
print(squares)
total = sum(score for score in scores.values())
print(total)
even_squares = (n * n for n in range(10) if n % 2 == 0)
print(list(even_squares))- [x for x in items] builds a list.
- {k: v for k, v in pairs} builds a dictionary.
- {x for x in items} builds a set of unique values.
- (x for x in items) is lazy and produced once.
Your turn
MediumSum the even squares
Print the sum of the squares of every even number from 1 to 20.
PYTHON · starter
# your code hereCheck your understanding before moving on.
Knowledge checkQuestion 1
Which expression is lazy and produces values only when needed?
Select an answer to continue
Study tools
Make it yours.
Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.
Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign inFinished reading?
Lock in what you just learned.
0%
Mark this lesson complete to save your place and move one step closer to the certificate.