GCGrowCarrer

List Comprehensions

Locked

Lesson 12 of 60 · Syntax · Medium

Finish these first:Lists →Functions →Or pass the tests below to unlock it now.

1

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.
Key words (tap to learn):
2

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.

3

Quick check

Before writing code: What should `even_squares([1,2,3,4])` return when your implementation of List Comprehensions is working?

4

Your challenge

2 sample tests, 1 hidden

Write even_squares(xs) returning squares of the even numbers, using a comprehension.

Stuck? Get a hint (free)
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.

Mastery0%

Learn this first