liveBook · Manning

Comprehension

As explained in Python How-To

A list comprehension is Python syntax for constructing a list by iterating over an iterable and optionally filtering or transforming its items.

Need a list of values derived from an iterable? A list comprehension creates it in one expression: `[expression for item in iterable]`. The expression determines each value in the new list. This often reads more clearly than initializing a list and appending inside a loop. section 5.2.1

Extract and filter task titles

```python from collections import namedtuple Task = namedtuple('Task', 'title, description, urgency') tasks = [ Task('Homework', 'Physics and math', 5), Task('Laundry', 'Wash clothes', 3), Task('Museum', 'Egypt exhibit', 4), ] titles = [task.title for task in tasks] urgent_titles = [task.title for task in tasks if task.urgency > 3] assert titles == ['Homework', 'Laundry', 'Museum'] assert urgent_titles == ['Homework', 'Museum'] ``` The expression `task.title` selects what goes into the result; the trailing `if` selects which tasks contribute a value. section 5.2.1 section 5.2.4

Choose the form that matches the container you need:

  • Use square brackets for a list. Add `if condition` after the iterable when only some items should contribute values. section 5.2 section 5.2.4
  • Use a set comprehension to create a set of derived values; duplicate results are removed. Dictionary comprehensions likewise create dictionaries from iterables. section 5.2.3 section 5.2.6
  • For nested data, put the outer `for` before the inner `for`, as you would with nested loops. Keep to at most two layers for readability. section 5.2.5
numbers = [-3, -2, -1, 0, 1, 2, 3]
 
squares = {x*x for x in numbers}
 
assert squares == {0, 9, 4, 1}    #1

Squaring both negative and positive numbers produces repeated values; the set comprehension retains each result once. section 5.2.3

Use a constructor instead when the items need no transformation: `set(numbers)` is simpler than `{x for x in numbers}`. If the expression or nesting becomes hard to follow, use ordinary loops. A list comprehension is also usually less verbose than constructing a list with `map`; an iterator from `map` can still suit a loop that performs several operations. section 5.2.6 section 7.2.2

How Python How-To covers it

How deep it goes
Explains expression and filter syntax, compares loops, and works through nested iteration while discouraging more than two layers.
Examples
Uses task titles and urgency filtering, squares with duplicate set results, and nested task data.
What it assumes
Builds on familiarity with lists and for loops while explaining iterables and briefly reminding readers what named tuples are.
What you can do after
Build it from scratch to transform or filter iterables into containers, choosing constructors or loops when they read better.
How it connects
Connects iterables and for loops to container constructors, map, and generator expressions.

Also explained in

Compare how 6 books explain comprehension →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python How-To. The section links point to the parts of the book it draws on.