Python 3.6Code walkthrough8 parts

Comprehensions

Build lists, sets and dicts in one readable line.

Loading your progress…Next: 4.1 Defining Functions

In this lesson8 parts

  1. 01Four lines, or one
  2. 02The comprehension is the loop
  3. 03Filtering with a condition
  4. 04Choosing a value, and choosing an item
  5. 05Set and dictionary comprehensions
  6. 06Reading a comprehension
  7. 07When a plain loop is clearer
  8. 08Recap, your challenge, and the module

Key terms

The words this lesson introduces, each in one line. The module’s glossary collects them all.

dictionary comprehension
A dictionary built from a key and a value evaluated for each item: {item: price for item, price in zip(items, prices)}.
list comprehension
A list built from an expression evaluated for each item of an iterable: [round(p * 1.08, 2) for p in prices], with an optional if at the end to filter.
set comprehension
A set built from an expression evaluated for each item: {len(item) for item in items}.

Quiz 5 questions

Your first pick on each question is the one that counts, and a right one earns a coin. Getting one wrong here is how the lesson sticks.

Practice

Problems to solve in your own notebook. Each states the problem, not the steps: working out the steps is the exercise. Level A applies the lesson, B combines it with earlier ones, C stretches it.

The self-checking notebook for this lesson is Notebook 3 · Strings and Comprehensions.

Common mistakes

What you will see when it goes wrong, why it happens, and the fix.

Where it’s used

Where this lesson’s ideas turn up in real work.