CHAPTER 13 · BEGINNER4 min read

Comprehensions

Build new collections with concise transformations and filters while keeping the rule readable.

Python 3.12+Free to readModule 3 of 13
YOUR NEXT SMALL WINS

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.

squares_two_ways.py🐍Python
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

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.

clean_topics.py🐍Python
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

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.

label_or_filter.py🐍Python
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

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.

comprehension_containers.py🐍Python
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.
LET IT CLICK

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.
TURN UNDERSTANDING INTO SOMETHING YOU CAN DO

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.

01

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.

your_turn_1.py🐍Python
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.
Explore a worked solution
one_possible_solution.pyPython
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].

02

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.

your_turn_2.py🐍Python
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.
Explore a worked solution
one_possible_solution.pyPython
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.

A SMALL QUESTION. A USEFUL NEXT STEP.

What stayed with you?

Check the ideas while they’re fresh. Your answers stay in this page and feedback appears as you go.

A LITTLE ACTIVE RECALL0 / 3 answered
01Which expression keeps only positive source numbers and squares them?
02For three input scores, how many items does ['pass' if s >= 60 else 'practice' for s in scores] produce?
03What should you expect if two dictionary comprehension items produce the same key?
⚡CODING CHALLENGE
🔒Required to Mark Lesson Complete

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.

EXPECTED OUTPUT
[Process exited with code 0 - No output]
challenge.pyPython 3
Ctrl + ↵
Execution Console
Click "Run & Verify" (or press Ctrl + Enter) to test your code against the challenge.

Keep exploring.

The official references behind this chapter, when you want a second angle or the full details.

MODULE 03 · PRACTICAL SELF-CHECK

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 module

One chapter closer.

Reading is a start. Trying it yourself makes the connection.

Solve the hands-on coding challenge in the knowledge section to verify your code and unlock chapter completion.