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.
Make a list of the cubes of 1 to 5 using a comprehension and range.
Given words = ["sun", "moon", "star", "sky"], build a list of the words that start with "s", in upper case.
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
Rewrite a loop that appends squares of even numbers as a comprehension, and explain how to read it.
What is the difference between [n for n in nums if n > 2] and [n if n > 2 else 0 for n in nums]?
How does the order of two for clauses in a comprehension work?
Is the loop variable of a comprehension visible afterwards?
What does funcs = [lambda: i for i in range(3)] give when you call each function, and why?
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]]