Comprehensions
Build new collections with concise transformations and filters while keeping the rule readable.
By the end, you’ll be able to…
- Translate an append loop into a list comprehension.
- Distinguish filtering items from selecting a value for every item.
- Use dictionary and set comprehensions without hiding complicated control flow.
01A new collection from a simple rule
A list comprehension creates a new list by applying an expression to items from an iterable. Its shape is [expression for item in iterable]. Read the for part first to understand where each item comes from, then read the expression to see what enters the result. This is especially useful when the main purpose of a loop is to populate a new collection.
Compare the two versions below. The ordinary loop makes initialization and append explicit; the comprehension states the same transformation in one expression. Neither version changes the source list. A comprehension is not automatically better because it is shorter. Use it when the relationship between the input and output can be understood quickly, and retain an ordinary loop when several steps deserve names or explanation.
02Filter before adding a result
An optional if after the for clause filters source items. In [number * 2 for number in numbers if number > 0], only positive numbers contribute results. The output expression is evaluated for each item that passes the filter. The number of output items can therefore be smaller than the number of input items, and an empty input naturally produces an empty list.
Cleaning and filtering text is a practical example. First decide whether the source item is eligible, then state the cleaned form that belongs in the result. Be aware when the condition and expression repeat a costly or complicated operation. For small text values, repeating strip is easy to understand; for more involved work, an ordinary loop with a named intermediate result can be clearer.
03Choose a value without removing an item
A conditional expression has the form value_if_true if condition else value_if_false. Placed before the for clause, it selects what to include for every input item. This differs from a trailing filter, which decides whether an item contributes at all. Read the positions carefully: a filter reduces participation, while a conditional expression chooses between two result values.
Use the length of the result as a self-check. Labeling every score as pass or practice should preserve the number of scores. Selecting only passing scores may reduce it. Both rules involve an if, but they answer different questions. Conditional expressions work outside comprehensions too, yet deeply nested choices are difficult to read; a normal if statement is often the best place to explain several branches.
04Build mappings and unique groups
Dictionary comprehensions use {key_expression: value_expression for item in iterable}. Set comprehensions omit the colon and value expression. The result follows the same rules as a dictionary or set built another way: dictionary keys are unique, and sets discard duplicates. When multiple source items produce the same dictionary key, the later value for that key wins.
Choose the output container according to what information must survive. A list preserves order and duplicates, a set records unique values, and a dictionary connects identifiers to details. Avoid comprehensions whose main purpose is printing or mutating another object; they build an unnecessary collection and hide intent. If you cannot translate a comprehension into a simple ordinary loop and explain each part, rewrite it until you can.
The ideas worth keeping.
- A comprehension expresses a simple rule for constructing a new collection.
- A trailing if filters items; an if/else expression chooses each item's result.
- Lists, sets, and dictionaries preserve different information, so choose deliberately.
Make it yours.
Type and test your code right here in the interactive workspace. Run your solution, check the output, and compare with the worked guide when ready.
Convert selected temperatures
Given celsius = [-10, 0, 10, 20], build a list of Fahrenheit values for nonnegative Celsius entries only. Use the formula c * 9 / 5 + 32 and a comprehension.
Explore a worked solution
celsius = [-10, 0, 10, 20]fahrenheit = [c * 9 / 5 + 32 for c in celsius if c >= 0]print(fahrenheit)The filter includes zero and excludes -10 before the transformation contributes a result. The list is [32.0, 50.0, 68.0].
Create an item-length index
Given names = ['Ada', 'Mira', 'Noor', 'Ada'], create a dictionary mapping each name to its length and a set containing those lengths. Print the dictionary and the sorted lengths.
Explore a worked solution
names = ["Ada", "Mira", "Noor", "Ada"]length_by_name = {name: len(name) for name in names}lengths = {len(name) for name in names}print(length_by_name)print(sorted(lengths))The dictionary has one entry per unique name, and the set contains only 3 and 4. Duplicate source entries do not create duplicate keys or set members.
What stayed with you?
Check the ideas while they’re fresh. Your answers stay in this page and feedback appears as you go.
Convert selected temperatures
Given celsius = [-10, 0, 10, 20], build a list of Fahrenheit values for nonnegative Celsius entries only. Use the formula c * 9 / 5 + 32 and a comprehension.
[Process exited with code 0 - No output]
Keep exploring.
The official references behind this chapter, when you want a second angle or the full details.
Pause. Put the pieces together.
You’ve reached the end of Decisions and repetition. Before moving on, use this task to check what you can do independently.
Process a collection, handle a boundary value, and explain why the loop terminates.
Try it in your own environment and write down the result. This is a self-check; reading completion does not evaluate your code.
Review this moduleOne chapter closer.
Reading is a start. Trying it yourself makes the connection.