Skip to content
Tactiverge

Python reference

List comprehensions

Also called: [x for x in] · comprehension · map and filter

Definition

A list comprehension builds a new list from an existing sequence in one expression: [f(x) for x in items if condition].

Picture it

Read it as 'make a list of f(x), for every x in items, keeping only the ones where the condition holds'. It is ideal for converting units or filtering out bad readings, and usually faster and clearer than an append loop.

Worked example

What does [v * 1000 for v in [0.012, -1.0, 0.020, 0.015] if v >= 0] produce, and what is its sum?

  1. Keep non-negative readings: 0.012, 0.020, 0.015
  2. Convert to mA: 12.0, 20.0, 15.0
  3. Sum = 47

Answer[12.0, 20.0, 15.0], summing to 47.

✓ The number in this answer is recomputed from scratch by an automated test.

Common misconceptions

  • Misconception: Comprehensions are for building lists; use a normal loop when you only want side effects such as printing.
  • Misconception: Very long comprehensions with nested ifs are harder to read than a loop.