List Comprehensions
LockedLesson 12 of 60 · Syntax · Medium
Finish these first:Lists →Functions →Or pass the tests below to unlock it now.
The big idea
Build collections declaratively: [expr for x in it if cond]. Dict and set comprehensions work the same way.
Think of it like this: Think of syntax and expressions like labeled measuring cups in a kitchen: each cup holds a specific kind of ingredient, and operators combine them into a new measurement.
Read the lesson
Build collections declaratively: [expr for x in it if cond]. Dict and set comprehensions work the same way.
squares = [x*x for x in range(5) if x % 2 == 0] # [0, 4, 16]
index = {w: len(w) for w in ["a", "bb"]}
Prefer a comprehension for simple transforms; use a loop when logic gets complex.
Quick check
Before writing code: What should `even_squares([1,2,3,4])` return when your implementation of List Comprehensions is working?
Your challenge
Write even_squares(xs) returning squares of the even numbers, using a comprehension.
More learning tools(compare languages, visual guide, related lessons)
Compare with another language
Similar to java.streams (60% overlap). Comprehensions ~ stream `filter`/`map`/`toList`.
Visual walkthrough
A diagram, a step-by-step animation, and short captions for List Comprehensions.