liveBook · Manning

Comprehension

As explained in The Quick Python Book, Fourth Edition

A list comprehension is a Python expression that constructs a list by iterating over an iterable and optionally filtering or transforming its elements.

A comprehension is a compact way to build a new collection from an iterable. Use one when a for loop would visit items, transform or select them, and add the results to a list, set, or dictionary. section 8.9

A list comprehension has the form `[expression for variable in iterable if condition]`. The expression produces each result; the optional `if` keeps only items that meet its condition. Square brackets make the result a list. Use braces for a set, or put `key: value` before `for` to build a dictionary. section 8.9

Transform and filter

For `x = [1, 2, 3, 4]`, `[item * item for item in x]` produces `[1, 4, 9, 16]`. Add a condition—`[item * item for item in x if item > 2]`—and the result is `[9, 16]`. The first expression replaces a loop that appends each square to a new list. section 8.9

word_count = sum(len([word for word in line.split() if word.isalpha()]) 
                       for line in lines)

In this word-count expression, the list comprehension keeps only words for which `isalpha()` is true. Its length becomes one value in an enclosing generator expression summed across the lines. section 8.13.2

Try a comprehension when a loop's job is to produce a collection. If the result is consumed by an operation such as `sum`, consider a generator expression instead: it is similar but usually uses less memory. Reading every line of a large file into a list can also be a memory concern. section 8.14 section 8.13.2

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Defines list, set, and dictionary syntax and works through transformation and filtering, without descending into implementation internals.
Examples
Squares and filters a four-item list, builds a dictionary of squares, and filters alphabetic words in a word count.
What it assumes
Assumes familiarity with for loops, expressions, and Python collections; introduces comprehension syntax from a loop comparison.
What you can do after
Build it from scratch to transform or filter an iterable into a list, set, or dictionary.
How it connects
Links comprehensions to for loops, conditional filtering, generator expressions, and memory use.

Also explained in

Compare how 6 books explain comprehension →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.