Learning LibraryCore Coding LibraryTeens

List comprehensions in Python: build a list in one line

Make an empty list, loop, append. You've written that pattern a dozen times. A list comprehension says the same thing in one line, once you can read it.

The big idea

A list comprehension builds a new list by applying an expression to each item of a sequence, optionally keeping only the items that pass a condition.

See it in code

1The basics

Here is the familiar loop and its comprehension side by side. They produce identical lists:

python
daily_tees = [42, 57, 38, 64]
price = 38

revenues = []
for tees in daily_tees:
    revenues.append(tees * price)
print(revenues)

print([tees * price for tees in daily_tees])
Run it. Two ways to turn tees into revenue:
[1596, 2166, 1444, 2432]
[1596, 2166, 1444, 2432]

Read the comprehension as "tees * price, for each tees in daily_tees." The expression comes first, then the loop that feeds it.

2A step further

Add an if at the end to filter. Only items that pass the test make it into the new list:

python
stock = [12, 3, 25, 0, 8]
reorder_point = 10

low = [level for level in stock if level < reorder_point]
print("Low stock levels:", low)
print("Products running low:", len(low))
Run it. Which stock levels are low?
Low stock levels: [3, 0, 8]
Products running low: 3

Three of the five levels are below 10. The if clause filters; the expression at the front decides what gets stored.

3At Evergreen

Transform and filter together, and feed the result straight into a function. This totals the revenue from launch week's strong days:

python
daily_tees = [42, 57, 38, 64, 71, 95, 88]
price = 38
target = 60

strong = [tees * price for tees in daily_tees if tees >= target]
print("Strong-day revenue:", strong)
print(f"Total from strong days: ${sum(strong):,}")
print(f"Share of the week: {sum(strong) / (sum(daily_tees) * price):.0%}")
Run it. Revenue from days that beat the target:
Strong-day revenue: [2432, 2698, 3610, 3344]
Total from strong days: $12,084
Share of the week: 70%

Four days out of seven produced 70% of the week's revenue. One line picked them out and converted them.

The same idea, everywhere

Comprehensions suit any "make a list from a list" job: codons from a strand, returns from prices, cleaned fields from raw text.

Try it yourself

Write a comprehension that produces every SKU for two colors and three sizes, using two for clauses. Then decide honestly whether that one is easier to read than nested loops.

The common mistake

Cramming too much into one line. A comprehension with two loops, a condition, and a function call is harder to read than the loop it replaced. If you have to read it twice, write the loop.

What it unlocks

Comprehensions compress the patterns from list methods and for loops, often over a range.