Reading List Comprehensions

A list comprehension builds a list by iterating, optionally selecting items, and evaluating the requested result expression for each selected item.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Read the iterable and filter first
  2. Preserve the intended calculation
  3. Read the iteration and filter before evaluating the result
  4. Compare with an explicit loop when the steps are hard to see

Read the iterable and filter first

Python [x * x for x in values if x >= 0] over minus 2, 3, and 0 yields 9 and 0. The condition skips the negative entry even though its square is positive. This is a filter followed by a transformation.

Preserve the intended calculation

If you need every squared value, remove that condition and expect 4, 9, and 0. A named mapping operation can explain a more domain-specific conversion when the expression outgrows a readable line.[1]

Read the iteration and filter before evaluating the result

In [len(word) for word in words if word.strip()], iteration chooses a word and the predicate checks whether its stripped spelling is nonempty. The result expression still measures the original word, including surrounding spaces. If the input is [" tea ", " ", "rice"], the output is 5 and 4, whereas measuring the trimmed words gives 3 and 4. Whitespace in text records explains why those results reflect different rules.

Compare with an explicit loop when the steps are hard to see

An ordinary loop can name the stripped word, skip it when empty, and append the measured value. Translating to a comprehension can preserve that sequence when its structure stays clear. A mapping pass and a filtering pass can help you derive the expected result before combining them.

Check whether a function in the result expression runs for discarded items. The selection predicate can prevent it from being evaluated at all. If computation creates effects or must produce diagnostics for discarded items, put that work at a deliberate point. Test with one passing value and one input you expect the comprehension to skip.

References

  1. Python Software Foundation, Python Tutorial: Control Flow ↩