all Python 3Lists (list)term
Conditional list comprehension
comprehension
A filtering if at the end of a list comprehension selects items by a condition. Not to be confused with the ternary operator (if ... else ...) at the start of the expression — that one transforms rather than filters.
Syntax
[выражение for x in iterable if условие]
The filtering if goes after the for and takes no else: [x if x > 0 for x in lst] is a SyntaxError, while [x if x > 0 else 0 for x in lst] replaces values instead of dropping them. Both forms can coexist in one comprehension — the leading ternary transforms, the trailing if selects.
Examples
lst = [1, -2, 3, -4, 5]
print([x for x in lst if x > 0]) # → [1, 3, 5]
print([x**2 for x in lst if x % 2 != 0]) # → [1, 9, 25]
words = ["apple", "hi", "banana", "ok"]
print([w for w in words if len(w) > 3]) # → ['apple', 'banana']
print([x if x > 0 else 0 for x in lst]) # → [1, 0, 3, 0, 5] (тернарный)
See also
Open in the full glossarydocs.python.orgReport an inaccuracy