List, filter and conditional comprehensions
Change the filter to n > 2 or the labels to your own words, and predict the output before running.
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
squares: [1, 4, 9, 16, 25, 36]
evens: [2, 4, 6]
labels: ['odd', 'even', 'odd', 'even', 'odd', 'even']
upper: ['APPLE', 'BANANA', 'CHERRY', 'AVOCADO']
long words: ['Banana', 'cherry', 'avocado']
pairs: [(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b'), (3, 'a'), (3, 'b')]
flat: [1, 2, 3, 4, 5, 6]
sum of squares: 91