Day 20 · ~15m

Python List Comprehensions: Filter and Transform in One Line

List comprehensions let you filter and transform data in a single, readable line. Replace your loops with comprehensions and write Python like a pro.

student (thinking)

On Day 14 you had me write a function that looped through a list of tuples and filtered out the bad ones. It was five lines of code just to build a list. Then we moved on to dictionaries. But I keep thinking—there has to be a shorter way to write that filter-and-build pattern. It feels so common.

teacher (amused)

You're reading the mind of every Python developer. Here's the secret: Python has a shortcut that lets you write the loop and the filter in a single line. It's called a list comprehension. And once you see it, you'll use it everywhere.

student (curious)

In one line? How?

teacher (focused)

Let me show you the before and after. Remember collect_valid_sales from Day 14? It looked like this:

def collect_valid_sales(raw_sales):
    valid = []
    for name, amount_str in raw_sales:
        amount = float(amount_str)
        if is_valid_sale(name, amount):
            valid.append((name, amount))
    return valid

Five lines to filter a list. Now watch what the same logic looks like as a comprehension:

def collect_valid_sales(raw_sales):
    return [float(amount_str) for name, amount_str in raw_sales if is_valid_sale(name, float(amount_str))]

One line. Same result. This is not magic—it's just grammar. A comprehension reads the for loop and the if check and smooshes them together in a way your brain learns instantly.

student (confused)

Wait, that's... hard to read. Isn't the five-line version clearer?

teacher (encouraging)

Right now, yes. You're still learning the pattern. But by the end of this week, you'll read comprehensions as naturally as you read loops. And once you do, they're way clearer than typing .append() five times. Plus, they're faster. The Python interpreter optimizes them.

student (excited)

OK so the pattern is: [thing for item in list if condition]. What does each part mean?

teacher (proud)

** Perfect breakdown. Let me unpack it:

  • thing — what you want in the output list (usually the item, or a transformation of it)
  • for item in list — the loop part (same as a regular for loop)
  • if condition — optional filter (only include items where this is True)

Here's a tiny example. Say you have a list of numbers and you want only the even ones:

numbers = [1, 2, 3, 4, 5, 6]
evens = [n for n in numbers if n % 2 == 0]
print(evens)  # [2, 4, 6]

Breaking it down:

  • n — the thing (just the number itself)
  • for n in numbers — loop through all numbers
  • if n % 2 == 0 — keep only numbers where the remainder is 0 (i.e., even)

Result: a new list with only the even numbers.

student (focused)

OK so today's problem is filtering a list of sales dictionaries to only the high-value ones. And I can use a comprehension instead of a for loop?

teacher (focused)

Exactly. You have a list of sale records—each one a dictionary with 'name', 'amount', 'region' keys. You want to filter to only the ones where amount >= 1000. Here's the for-loop version:

def get_high_value_sales(records):
    result = []
    for record in records:
        if record['amount'] >= 1000:
            result.append(record)
    return result

And here's the comprehension:

def get_high_value_sales(records):
    return [record for record in records if record['amount'] >= 1000]

One line vs. five. Same logic, same result.

student (amused)

This is basically the for loop and the if check squished into one line. I'm reading the comprehension from left to right: [record (the thing), for record in records (the loop), if record['amount'] >= 1000] (the filter). And my brain... yeah, I think I get it.

teacher (proud)

That's the aha moment. You're reading it correctly. And wait until tomorrow—we'll show you that comprehensions can transform data too, not just filter. You can do [record['name'] for record in records if record['amount'] >= 1000] to get just the names of high-value customers, or even [{'name': r['name'], 'amount': r['amount']} for r in records if r['amount'] >= 1000] to reshape the data in a single line. But that's tomorrow. Today, stick with filtering.

student (thinking)

So comprehensions are fast, they're compact, and they do loops + filtering in one line. Is there a case where I should not use a comprehension?

teacher (focused)

Good question. If your logic gets too complex—multiple nested conditions, or you need to do something that doesn't fit the [thing for item if condition] pattern—a regular for loop is clearer. Comprehensions are powerful, but they have a limit. You'll develop taste for when to use each one.

student (proud)

Got it. So tomorrow we learn transformations. And next week we're applying this to the real, huge spreadsheet your manager sends?

teacher (proud)

Next week you're filtering thousands of rows in a single line and getting instant answers. That's when this starts to feel powerful. Today: learn the syntax. Tomorrow: learn what it can do beyond filtering. Then you're ready for the volume test.