Python Foundations·Build real programs

Comprehensions and generators

Transform collections in one expression and stream values lazily.

Beginner 13 min read Lesson 11 of 480 Challenge included
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.

comprehensions.pyPython
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

Sum the even squares

Medium

Print the sum of the squares of every even number from 1 to 20.

PYTHON · starter
# your code here
Check 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 in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Next: Classes and dataclasses
Lesson 11 of 480 · 0% of course