Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 4.7 — List, Dict and Set Comprehensions
Python · Example 2 of 3

Dict and set comprehensions, and scope

In the last lines, [0] * 3 makes a list of three zeros, and the comprehension builds a fresh row each time. Topic 4.9 explains why that matters.

A comprehension builds a new list, dictionary or set from another collection in one readable line: what to produce, where to take items from, and an optional filter. It replaces the common loop-and-append pattern, as long as it stays short enough to read at a glance.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Make a list of the cubes of 1 to 5 using a comprehension and range.

02

Given words = ["sun", "moon", "star", "sky"], build a list of the words that start with "s", in upper case.

03

Given prices = {"pen": 10, "book": 80, "bag": 500}, build a new dictionary with every price increased by 10 percent (use price * 1.1 and round(..., 2)).

Explain it without notes

01

Rewrite a loop that appends squares of even numbers as a comprehension, and explain how to read it.

02

What is the difference between [n for n in nums if n > 2] and [n if n > 2 else 0 for n in nums]?

03

How does the order of two for clauses in a comprehension work?

04

Is the loop variable of a comprehension visible afterwards?

05

What does funcs = [lambda: i for i in range(3)] give when you call each function, and why?

Dict and set comprehensions, and scope
Sign in to run this example in your browser.

Expected output

lengths: {'apple': 5, 'Banana': 6, 'cherry': 6, 'avocado': 7}
initials: ['a', 'b', 'c']
cheap: {'apple': 30, 'banana': 12}
flipped: {30: 'apple', 12: 'banana', 50: 'mango'}
squares: [0, 1, 4, 9] | x is still outer
independent rows: [[1, 0, 0], [0, 0, 0]]