Lesson explanation
After this lesson, you will be able to:
if filter.for loop.You already know how to build a new list using for and append(). A list comprehension expresses a simple transformation or filter in a single readable expression:
new_values = [expression for item in source]The expression comes first and determines the values added to the new list. The for part supplies one item at a time. Adding if condition at the end keeps only items that satisfy a rule:
new_values = [expression for item in source if condition]The expression and filter can use Python features you already learned, such as string methods, comparisons, enumerate(), and f-strings. A comprehension creates a new list; it does not modify the source list. If the input is empty or no items qualify, the result is an empty list.
Use comprehensions for one clear transformation or filter. For multiple side effects, complex branching, or a longer workflow, an ordinary for loop is often easier to read.
The expression on the left determines what goes into the result. The source list stays unchanged.
prices = [12, 7, 20]
doubled = [price * 2 for price in prices]
print(doubled)
print(prices)Output:
[24, 14, 40]
[12, 7, 20]Each price produces exactly one new value.
A trailing if filters the values before they enter the new list.
cpu_percentages = [25, 77, 91, 43]
high_usage = [value for value in cpu_percentages if value > 70]
print(high_usage)Output:
[77, 91]If none of the values passed the test, the result would be [].
The expression can call string methods on each value.
raw_teams = [" Core ", "SUPPORT"]
team_keys = [team.strip().lower() for team in raw_teams]
print(team_keys)Output:
['core', 'support']Every new string is cleaned while the source strings remain unchanged.
A comprehension can reuse enumerate() and f-strings from earlier lessons.
checks = ["lint", "unit-test"]
labels = [f"{number}. {check}" for number, check in enumerate(checks, start=1)]
print(labels)Output:
['1. lint', '2. unit-test']A numbered report can be built without manually tracking an index.
| Purpose | Pattern |
|---|---|
| Transform values | [transform(item) for item in items] |
| Filter values | [item for item in items if condition] |
| Transform and filter | [expression for item in items if condition] |
| Number and format values | [f"{n}: {item}" for n, item in enumerate(items, start=1)] |
if goes after the for clause.print() or other side effects. Use a regular for loop in that situation.