Python List Comprehension
A list comprehension is a concise, one-line way to build a new list by transforming or filtering the items of an existing sequence.
Why use a comprehension?
Often you build a new list by looping over an existing one, applying some change to each item, and appending the result. A list comprehension expresses that whole pattern in a single readable line, which usually reads more clearly and runs a little faster than the equivalent multi-line loop.
From loop to comprehension
numbers = [1, 2, 3, 4]
squares = [n * n for n in numbers]
print(squares)This produces [1, 4, 9, 16]. The expression n * n runs for every n in numbers, and each result becomes an item in the new squares list. The original numbers list is left unchanged.
The syntax
The general form is [expression for item in iterable if condition]. The expression decides what goes into the new list, the for clause supplies each item, and the optional if clause filters which items are kept.
Filtering with a condition
nums = [5, 12, 7, 20, 3]
big = [n for n in nums if n > 10]
print(big)Only items greater than 10 pass the condition, so big becomes [12, 20]. Items that fail the if clause are simply skipped and never added.
Transforming values
Applying a transformation
words = ["apple", "kiwi", "banana"]
upper = [w.upper() for w in words]
print(upper)- Transform every item: [x * 2 for x in values].
- Filter items: [x for x in values if x > 0].
- Do both at once: [x * 2 for x in values if x > 0].
- Use a conditional expression: ['even' if x % 2 == 0 else 'odd' for x in values].