
A list comprehension constructs a new list from an iterable in one expression. The basic form is [expression for item in iterable]: Python visits each item, evaluates the expression, and appends the result.
squares = [n * n for n in range(8)] # [0, 1, 4, 9, 16, 25, 36, 49]
The expression controls what goes into the list; it need not be the item itself. Transform each record into the exact value the next part of the program needs:
names = [user.name for user in users]
For a transformation that needs more than one input value, unpack each iterable element directly in the comprehension:
coordinates = [(x, y) for x, y in points]
That form makes the expected shape of points explicit. If its elements do not contain exactly two values, Python raises ValueError rather than silently producing malformed output.
A comprehension creates a new list; it does not modify the source iterable. Keep the expression readable enough that the mapping is obvious at a glance. For a small calculation, one line is efficient. For a transformation with several steps or side effects, use a loop.
Now loading...
Filtering elements with precision
Add a trailing if clause to keep only the elements that satisfy a condition. The test runs once for each item, before the result expression is evaluated:
evens = [n for n in range(12) if n % 2 == 0] # [0, 2, 4, 6, 8, 10]
The condition filters; it does not transform. To select positive values and then convert them, put the transformation before the for and the test after it:
absolute_values = [abs(n) for n in measurements if n >= 0]
Multiple filters can be written as separate clauses. Every condition must be true for an item to reach the expression:
usable_names = [
user.name.strip()
for user in users
if user.active
if user.name is not None
]
Separate clauses can make the filtering sequence explicit, but ordinary boolean operators are often clearer when the tests form one condition:
usable_names = [
user.name.strip()
for user in users
if user.active and user.name is not None
]
Order matters when a later test depends on an earlier test keeping the value safe. In the first version, the active check does not protect access to user.name; the null check only protects the call to strip. Write the condition so every attribute access and operation is valid for the values that reach it.
A conditional expression has different behavior from a filter. It keeps one output for every input, choosing between two values:
labels = ["ready" if job.done else "pending" for job in jobs]
Use a filter when rejected items should disappear. Use a conditional expression when each item should produce a result, even if the result differs by case.
Reading nested comprehensions from the inside out
Each additional for clause adds a loop. Read the clauses from left to right as nested loops, with the first clause outermost and the last clause innermost:
pairs = [
(left, right)
for left in "AB"
for right in (1, 2, 3)
]
# [('A', 1), ('A', 2), ('A', 3),
# ('B', 1), ('B', 2), ('B', 3)]
The equivalent loops make the traversal order explicit:
pairs = []
for left in "AB":
for right in (1, 2, 3):
pairs.append((left, right))
For each value of left, Python visits every value of right before advancing left. That order determines both the output order and which combinations are produced.
With nested data, the inner iterable often depends on the outer item. This comprehension flattens rows into a single list:
matrix = [[1, 2], [3, 4], [5, 6]] values = [value for row in matrix for value in row] # [1, 2, 3, 4, 5, 6]
Its loop equivalent is again a direct translation: iterate over each row, then over each value in that row. A filter placed after both clauses tests each value; a filter between them can reject an outer item before the inner loop begins:
positive_values = [
value
for row in matrix if any(value > 0 for value in row)
for value in row
if value > 0
]
Nested comprehensions can encode substantial control flow in a compact expression. When the source or condition is hard to track, expand the clauses mentally—or write the equivalent loops—to verify the iteration order and the point at which each filter runs.
Knowing when a loop is the better tool
A comprehension is a good fit when each input independently either produces one value or is discarded. Use a loop when the work has steps that need names, intermediate state, or their own error handling. For example, parsing and validating records is easier to inspect when each decision has a place to live:
parsed = []
rejected = []
for line_number, line in enumerate(lines, start=1):
text = line.strip()
if not text:
continue
try:
value = int(text)
except ValueError:
rejected.append((line_number, text))
continue
if value 0:
rejected.append((line_number, text))
continue
parsed.append(value)
A comprehension can call a function, but it is a poor vehicle for work whose purpose is a side effect. This expression builds an otherwise unused list just to print each name:
unused = [print(user.name) for user in users]
The loop states the operation directly and avoids allocating that list:
for user in users:
print(user.name)
Loops also make early termination explicit. A comprehension always consumes its iterable to construct the result; use a loop when finding one match should stop the search:
match = None
for record in records:
if record.key == target:
match = record
break
Use a generator expression with next when the search is a simple extraction and the default behavior is sufficient:
match = next(
(record for record in records if record.key == target),
None,
)
When each item updates several pieces of state, the loop keeps those updates together and makes their order visible:
totals = {}
counts = {}
for category, amount in transactions:
totals[category] = totals.get(category, 0) + amount
counts[category] = counts.get(category, 0) + 1
That stateful work can be forced into a comprehension, but the resulting expression hides its purpose and usually creates a throwaway list. Prefer the loop when a reader must understand not only which values are selected, but how processing changes the program as it proceeds.
Source: https://www.pythonfaq.net/how-to-use-list-comprehensions-in-python/



