List Comprehension
Python · Lists
Theory
A list comprehension builds a new list in a single expression: [expression for item in iterable if condition]. Python loops over the iterable, skips items where the optional condition is false, evaluates the expression for each remaining item and collects the results. [x*x for x in range(10) if x % 2 == 0] keeps 0, 2, 4, 6 and 8 and squares them, giving [0, 4, 16, 36, 64]. It is equivalent to creating an empty list, looping, testing and appending, just shorter.
Comprehensions are usually a little faster than the equivalent for loop with append(), because the looping happens inside optimised interpreter code. The loop variable stays inside the comprehension and does not overwrite an outside variable. Put if after the for to filter; put a conditional expression in front to transform every item, e.g. ['even' if x % 2 == 0 else 'odd' for x in nums]. Dict and set comprehensions work the same way.
Why we use it
Transforming and filtering a collection is one of the most common tasks in data work: clean every name, keep sales above a target, square numbers. A comprehension expresses the whole intent in one readable line.
When to use it
Use a comprehension when building a new list from another iterable with a simple transform or filter. If the logic needs several statements, try/except or side effects like printing, write a normal for loop instead. For huge data, a generator (x for x in ...) avoids building the whole list in memory.
How it works
- Start an empty result list
- Take the next x from range(10)
- Does x % 2 == 0 hold? Yes: Compute x*x and add it to the result. No: Skip this x.
- Any items left in the iterable? Yes: Go back and take the next x. No: Stop looping.
- Return the finished list [0, 4, 16, 36, 64]
Syntax
[expression for item in iterable if condition]Example
squares = [x*x for x in range(10) if x % 2 == 0]Key points
- More Pythonic and often faster than manual for-loops
- Can include an optional filter condition at the end
- Always creates a new list; the source is not changed
- Put if/else in front to transform every item, if at the end to filter
- The loop variable does not leak outside the comprehension
- Keep it short; complex logic belongs in a normal loop