Python List Comprehension: Filter, If-Else, Nested and Lambda

Say you’re closing out the day at an Austin coffee shop with eight order amounts, and you need each one with 8.25% sales tax. A Python list comprehension does it in one line: [round(a * 1.0825, 2) for a in orders].

The pattern is always [expression for item in iterable if condition]. It builds a new list and leaves the original alone.

In this guide, I’ll show you filtering, if-else, nested loops and lambdas, plus dict and set versions. Every example ran on Python 3.12.5.

The sample orders we’ll use for list comprehension

Here’s one day of orders in dollars. Every example below starts from this list:

orders = [12.50, 48.00, 7.25, -15.00, 23.40, 0.00, 19.99, 64.10]
  • Five normal sales, from $7.25 to $64.10
  • A $15.00 refund, stored as a negative number
  • A free drink stored as $0.00

The refund and the free drink are the tricky ones; a good comprehension filters or labels them. New to lists? See creating a list in Python.

Method 1: Transform every item with a list comprehension (Recommended)

This is the basic form, and it replaces the usual for loop in Python that appends to an empty list.

Here’s the loop and the comprehension side by side:

orders = [12.50, 48.00, 7.25, -15.00, 23.40, 0.00, 19.99, 64.10]

taxed = []
for amount in orders:
    taxed.append(round(amount * 1.0825, 2))

taxed2 = [round(amount * 1.0825, 2) for amount in orders]
print(taxed2)
print(taxed == taxed2)

Output:

[13.53, 51.96, 7.85, -16.24, 25.33, 0.0, 21.64, 69.39]
True

Both give the same eight amounts, so it prints True.

Command Prompt output of a Python list comprehension adding 8.25 percent sales tax to eight coffee shop orders
The comprehension adds sales tax to all eight orders and matches the for loop result exactly.

How does this code work?

Python runs for amount in orders, evaluates round(amount * 1.0825, 2) for each value and collects the results.

So here’s the catch: the refund gets taxed too and becomes -16.24. That’s where a filter comes in.

Method 2: Filter a list with an if condition

Put an if after the loop and only matching items make it into the new list. Same eight orders here:

orders = [12.50, 48.00, 7.25, -15.00, 23.40, 0.00, 19.99, 64.10]

big = [amount for amount in orders if amount > 20]
print(big)
print(f"{len(big)} orders over $20, total ${sum(big):,.2f}")

Output:

[48.0, 23.4, 64.1]
3 orders over $20, total $135.50

How does this code work?

Each amount is tested against amount > 20. Only $48.00, $23.40 and $64.10 pass, for a total of $135.50.

For other ways to do this, like filter(), see filtering lists in Python.

Method 3: Use if-else inside a list comprehension

To keep every item but change some, put the if-else before the for, not after it.

orders = [12.50, 48.00, 7.25, -15.00, 23.40, 0.00, 19.99, 64.10]

labels = ["refund" if a < 0 else "comp" if a == 0 else f"${a:.2f}" for a in orders]
print(labels)

try:
    compile('[a for a in orders if a > 0 else 0]', 'demo', 'eval')
except SyntaxError as err:
    print("SyntaxError:", err.msg)

Output:

['$12.50', '$48.00', '$7.25', 'refund', '$23.40', 'comp', '$19.99', '$64.10']
SyntaxError: invalid syntax
Command Prompt output of a Python list comprehension with if-else labeling refunds and comps, then a SyntaxError
The if-else version labels the refund and the free drink, while putting else after the loop raises a SyntaxError.

How does this code work?

The part before for is an ordinary conditional expression, so every order gets a label: “refund”, “comp” or a dollar string.

An if at the end is a filter, and filters can’t have an else. That’s why the second line fails. There’s more in list comprehension with if-else.

Method 4: Use nested loops in a list comprehension

You can stack for clauses. Here the same orders are split into Monday and Tuesday:

days = [[12.50, 48.00, 7.25, -15.00],     # Monday
        [23.40, 0.00, 19.99, 64.10]]      # Tuesday

sales = [a for day in days for a in day if a > 0]
print(sales)
print(f"{len(sales)} paid orders, total ${sum(sales):,.2f}")

Output:

[12.5, 48.0, 7.25, 23.4, 19.99, 64.1]
6 paid orders, total $175.24

How does this code work?

The outer loop runs first, then the inner one, like two indented loops. The if drops the refund and the free drink, leaving six paid orders worth $175.24.

This is also how you flatten data, which I cover in flattening a list of lists.

Method 5: Use a lambda or function in a list comprehension

You can call any function in the expression, including a lambda. Same orders, refunds and comps skipped:

orders = [12.50, 48.00, 7.25, -15.00, 23.40, 0.00, 19.99, 64.10]

add_tax = lambda a: round(a * 1.0825, 2)
print([add_tax(a) for a in orders if a > 0])
print(list(map(add_tax, filter(lambda a: a > 0, orders))))

funcs = [lambda: a for a in orders[:3]]   # trap: every lambda sees the last a
print([f() for f in funcs])
funcs = [lambda a=a: a for a in orders[:3]]
print([f() for f in funcs])

Output:

[13.53, 51.96, 7.85, 25.33, 21.64, 69.39]
[13.53, 51.96, 7.85, 25.33, 21.64, 69.39]
[7.25, 7.25, 7.25]
[12.5, 48.0, 7.25]
Command Prompt output of a Python list comprehension calling a lambda, the map and filter version, and the lambda late binding trap
The lambda gives the same taxed values as map and filter, and the default-argument fix stops every lambda returning 7.25.

How does this code work?

add_tax is just a function stored in a variable, as in lambda functions in Python. It reads better than the map() function plus filter() combo.

The trap is creating lambdas in a loop. They look up a when called, after the loop ends, so all three return 7.25. a=a freezes each value.

What about dict, set and generator comprehensions?

The same syntax works with other brackets:

orders = [12.50, 48.00, 7.25, -15.00, 23.40, 0.00, 19.99, 64.10]

print({n: a for n, a in enumerate(orders, 1) if a > 20})     # dict comprehension
print({round(a) // 10 * 10 for a in orders if a > 0})        # set comprehension
print(sum(a for a in orders if a > 0))                        # generator expression

Output:

{2: 48.0, 5: 23.4, 8: 64.1}
{0, 40, 10, 20, 60}
175.23999999999998
Command Prompt output of a Python dictionary comprehension, set comprehension and generator expression on coffee shop orders
Curly braces give a dict or a set, and parentheses inside sum() give a generator that totals the paid orders.

How does this code work?

{n: a ...} maps order numbers to amounts, and the set keeps each $10 bucket once. The sum prints 175.23999999999998, which is float noise, so wrap it in round(..., 2). Dict comprehensions get their own guide: dictionary comprehension in Python.

Pro Tip: When you only need a total, drop the brackets. The generator feeds sum() without building a list.

Picking the right list comprehension pattern

PatternUse it when
[f(x) for x in items]Changing every item
[x for x in items if cond]Keeping some items
[a if cond else b for x in items]Keeping all items, changing some
[x for row in rows for x in row]Looping over nested data
sum(x for x in items)You only need one result

Things to Keep in Mind With List Comprehensions

  • Filter if goes after the loop; if-else goes before it. Mixing them up raises a SyntaxError.
  • Float sums pick up noise like 175.23999999999998, so round money values or use Decimal.
  • Lambdas made in a loop share the last value. Use a default argument.
  • If it doesn’t fit on one or two lines, a plain for loop is easier to read.

A few more list guides that pair well with this one:

Frequently asked questions

What is a list comprehension in Python?

It’s a one-line way to build a new list: [expression for item in iterable if condition].

Is a list comprehension faster than a for loop?

Usually a little, since it skips repeated append() calls. Pick it for readability.

Can I use if-else in a list comprehension?

Yes. Put it before the for: [a if a > 0 else 0 for a in orders]. An if after the for is a filter and can’t have else.

Can a list comprehension call a lambda?

Yes, though a named function or a plain expression is usually clearer.

What’s the difference between a list comprehension and a generator expression?

Brackets build the whole list in memory; parentheses make a generator that yields values one at a time.

Where are list comprehensions documented?

See List Comprehensions in the Python tutorial.