Skip to content
Python

Python List, Dict and Set Comprehensions with if, else and Nested Loops

Ihsan Ullah · 12 min read
Python list comprehension, Lesson 21 of the Python course: list, dict and set comprehensions with if and else

Python course · Module 4: Data structures · Lesson 21 of 63

Quick answer: A list comprehension builds a new list in one line: [price + 50 for price in prices] adds 50 to every price. An if at the end keeps only some items: [price for price in prices if price < 100]. Curly braces make a set, {tag.lower() for tag in tags}, and curly braces with key: value make a dictionary, {name: len(name) for name in names}.

In this lesson you will learn:

  • how to turn a for loop with append() into a list comprehension
  • how to filter with if, and choose a value with if and else
  • how to build dictionaries and sets with comprehensions
  • how to use two for clauses, and when a plain loop is clearer
  • what a generator expression is

Before you start: finish Lesson 20, Python String Methods and Slicing: split(), join(), strip() and Reversing Strings. You also need the one-line x if condition else y from Lesson 11, Python if, elif and else Statements (and match). All examples were tested on Python 3.14.6 and gave the same output on Python 3.15.2, the newest release on python.org, apart from one memory address.

From a for loop to a list comprehension

You met append() in Lesson 15, and in Lesson 20 you called it inside a loop to build a list. A list comprehension does the same job in one line. Here we add 50 rupees to every price in the shop’s price list:

prices = [450, 60, 40, 3200]

new_prices = []
for price in prices:
    new_prices.append(price + 50)
print(new_prices)

new_prices = [price + 50 for price in prices]
print(new_prices)
print(prices)
[500, 110, 90, 3250]
[500, 110, 90, 3250]
[450, 60, 40, 3200]

Both ways give the same list. Read the comprehension as “price + 50, for every price in prices”. The square brackets say “make a list”, price + 50 is what goes into it, and the for clause is the for line from Lesson 12 without the colon. prices itself did not change: a comprehension always makes a new list. The Python tutorial calls list comprehensions “a concise way to create lists”.

Python list comprehension, Lesson 21: a for loop with append() and the matching one-line list comprehension, with the brackets, the expression and the for clause linked by colour.
The same list built two ways. The comprehension keeps the loop’s parts but puts the expression first, inside square brackets. Both give [500, 110, 90, 3250].

The expression can be anything that gives a value:

names = ["Notebook", "Pen", "Ruler", "Backpack"]
print([name.upper() for name in names])
print([len(name) for name in names])
print([n * n for n in range(1, 6)])

prices = [450, 60, 40, 3200]
print(", ".join([str(price) for price in prices]))
['NOTEBOOK', 'PEN', 'RULER', 'BACKPACK']
[8, 3, 5, 8]
[1, 4, 9, 16, 25]
450, 60, 40, 3200

The last line finishes a job from Lesson 20: join() only accepts strings, and [str(price) for price in prices] turns every price into text in one step.

Filter items with if

Put an if after the for to keep only the items that pass a test:

prices = [450, 60, 40, 3200]
cheap = [price for price in prices if price < 100]
print(cheap)

names = ["Notebook", "Pen", "Ruler", "Backpack"]
print([name for name in names if len(name) > 5])
print([name.lower() for name in names if "e" in name])
[60, 40]
['Notebook', 'Backpack']
['notebook', 'pen', 'ruler']

The if is a filter: only prices that pass price < 100 go into the new list. The second line keeps names longer than five characters. The third keeps names that contain “e” and makes them lower case, so “Backpack” is dropped.

Choose between two values with if and else

To keep every item but change some of them, put if and else before the for, as part of the expression:

prices = [450, 60, 40, 3200]
labels = ["cheap" if price < 100 else "expensive" for price in prices]
print(labels)

sale = [price - 50 if price > 400 else price for price in prices]
print(sale)

big_sale = [price // 2 if price > 1000 else price - 10 for price in prices if price != 40]
print(big_sale)
['expensive', 'cheap', 'cheap', 'expensive']
[400, 60, 40, 3150]
[440, 50, 1600]

"cheap" if price < 100 else "expensive" is the conditional expression from Lesson 11. It picks a value for every price, so the new list is as long as prices. In big_sale both kinds are used: if price != 40 at the end removes the ruler, and the front part halves prices above 1000 with // (Lesson 6) and takes 10 off the rest. The rule:

  • if alone goes at the end and filters, so the list can get shorter.
  • if ... else goes at the front and chooses a value, so every item stays.

Putting else at the end is a common error:

prices = [450, 60, 40, 3200]
cheap = [price for price in prices if price < 100 else 0]
print(cheap)
  File "/home/learner/python-course/err1_if_else_at_end.py", line 2
    cheap = [price for price in prices if price < 100 else 0]
                                                      ^^^^
SyntaxError: invalid syntax

The filter part cannot have an else. Move the if/else to the front.

Dictionary comprehensions

A dict comprehension uses curly braces and a key: value pair before the for:

names = ["Notebook", "Pen", "Ruler", "Backpack"]
prices = [450, 60, 40, 3200]

price_of = {name: price for name, price in zip(names, prices)}
print(price_of)

sale = {name: price - 50 for name, price in price_of.items() if price > 400}
print(sale)

print({name: len(name) for name in names})
print({price: name for name, price in price_of.items()})
{'Notebook': 450, 'Pen': 60, 'Ruler': 40, 'Backpack': 3200}
{'Notebook': 400, 'Backpack': 3150}
{'Notebook': 8, 'Pen': 3, 'Ruler': 5, 'Backpack': 8}
{450: 'Notebook', 60: 'Pen', 40: 'Ruler', 3200: 'Backpack'}
  • The first pairs names with prices. zip() from Lesson 19 gives one (name, price) pair at a time, unpacked as in Lesson 16.
  • The second loops over .items(), as in Lesson 17, keeps prices above 400 and takes 50 off.
  • The last swaps keys and values. This is safe only when all values are different: if two products had the same price, the later one would replace the earlier one, because a key appears only once.

Set comprehensions

Curly braces without a colon make a set:

names = ["Notebook", "Pen", "Ruler", "Backpack"]
print({len(name) for name in names})

tags = ["Office", "school", "office", "Art", "SCHOOL"]
unique_tags = {tag.lower() for tag in tags}
print(sorted(unique_tags))
print(len(tags), len(unique_tags))

print(type({n: n * 2 for n in range(3)}))
print(type({n * 2 for n in range(3)}))
{8, 3, 5}
['art', 'office', 'school']
5 3
<class 'dict'>
<class 'set'>

The first set has three numbers, not four: “Notebook” and “Backpack” both have 8 letters, and a set keeps one copy (Lesson 18). In the tags example, lower-casing makes "school" and "SCHOOL" the same item. We print sorted(unique_tags) because the printed order of a set of strings can change between runs. The last two lines show the rule: with key: value you get a dict, without the colon a set.

Nested loops in a comprehension

A comprehension can have more than one for. This one makes every size and colour pair for a T-shirt:

sizes = ["S", "M"]
colours = ["red", "blue", "black"]

combos = [(size, colour) for size in sizes for colour in colours]
print(combos)
print(len(combos))

combos = []
for size in sizes:
    for colour in colours:
        combos.append((size, colour))
print(combos)
[('S', 'red'), ('S', 'blue'), ('S', 'black'), ('M', 'red'), ('M', 'blue'), ('M', 'black')]
6
[('S', 'red'), ('S', 'blue'), ('S', 'black'), ('M', 'red'), ('M', 'blue'), ('M', 'black')]

The for clauses run in the same order as nested loops, so the first for is the outer loop; the tutorial says “the order of the for and if statements is the same in both these snippets”. Two sizes times three colours gives six pairs.

A tuple expression needs its own round brackets:

sizes = ["S", "M"]
colours = ["red", "blue", "black"]
combos = [size, colour for size in sizes for colour in colours]
  File "/home/learner/python-course/err2_tuple_no_parens.py", line 3
    combos = [size, colour for size in sizes for colour in colours]
              ^^^^^^^^^^^^
SyntaxError: did you forget parentheses around the comprehension target?

Two for clauses are also the usual way to flatten a list of lists into one list:

orders = [["Pen", "Ruler"], ["Notebook"], ["Pen", "Backpack", "Pen"]]

all_items = [item for order in orders for item in order]
print(all_items)

others = [item for order in orders for item in order if item != "Pen"]
print(others)

table = [[row * col for col in range(1, 4)] for row in range(1, 4)]
print(table)
['Pen', 'Ruler', 'Notebook', 'Pen', 'Backpack', 'Pen']
['Ruler', 'Notebook', 'Backpack']
[[1, 2, 3], [2, 4, 6], [3, 6, 9]]

Read [item for order in orders for item in order] left to right: for every order, for every item in it, take the item. The last example is different: one comprehension sits inside another. The inner one builds a row and the outer one repeats it, so you get a list of lists.

When a plain loop is clearer

Comprehensions are for building a collection, not for doing something with each item:

names = ["Notebook", "Pen"]
result = [print(name) for name in names]
print(result)

for name in names:
    print(name)
Notebook
Pen
[None, None]
Notebook
Pen

result is a useless list of None values, because print() gives back None (Lesson 22 explains why). The plain loop says what you mean.

Long comprehensions are also hard to read. Both versions make the same stock report:

prices = {"Notebook": 450, "Pen": 60, "Ruler": 40, "Backpack": 3200}
stock = {"Notebook": 12, "Pen": 0, "Ruler": 30, "Backpack": 2}

report = [f"{n}: {'sold out' if stock[n] == 0 else stock[n] * p}" for n, p in prices.items() if p < 1000]
print(report)

report = []
for name, price in prices.items():
    if price >= 1000:
        continue
    if stock[name] == 0:
        report.append(f"{name}: sold out")
    else:
        report.append(f"{name}: {stock[name] * price}")
print(report)
['Notebook: 5400', 'Pen: sold out', 'Ruler: 1200']
['Notebook: 5400', 'Pen: sold out', 'Ruler: 1200']

The one-liner packs a filter, a choice, two lookups and an f-string into one line. In the loop each line does one thing (continue is from Lesson 13). A simple rule: if a comprehension does not fit on one short line, write a loop.

Generator expressions (a short look)

Write a comprehension with round brackets and you get a generator expression:

prices = [450, 60, 40, 3200]
stock = [12, 50, 30, 2]

print(sum([p * s for p, s in zip(prices, stock)]))
print(sum(p * s for p, s in zip(prices, stock)))
print(any(p > 1000 for p in prices))

doubled = (p * 2 for p in prices)
print(doubled)
print(list(doubled))
print(list(doubled))
16000
16000
True
<generator object <genexpr> at 0x7f3b31bc0e10>
[900, 120, 80, 6400]
[]
  • sum() adds up numbers. The first line builds a list and then adds it; the second gives the same 16000 without building a list, making the values one at a time.
  • When a generator expression is the only argument, its own brackets can go. The language reference says they “can be omitted in calls when the generator expression is the only positional argument”.
  • any() gives True if at least one item is true.
  • Printing a generator shows only a description; the hex memory address changes on every run.
  • A generator can be used only once, so the second list(doubled) is empty.

Use a generator expression when you need the values once, for example in sum(), max() or any(), and a list comprehension when you want to keep the list.

Try it yourself

Exercise 1: Pass or fail

marks = [45, 78, 90, 33, 61]. Make a list of the marks of 50 or more, and a list with "pass" or "fail" for every mark.

Exercise 2: Word lengths

words = ["sky", "python", "loop", "map", "comprehension"]. Build a dictionary of each word and its length, but only for words longer than three letters.

Exercise 3: Every student once

groups = [["Ali", "Sara"], ["Omar", "Ali"], ["Sara", "Hina", "Ali"]]. With one comprehension, build a set of all the names. Print them in alphabetical order, and how many there are.

Solutions

Solution 1

marks = [45, 78, 90, 33, 61]
passed = [mark for mark in marks if mark >= 50]
results = ["pass" if mark >= 50 else "fail" for mark in marks]
print(passed)
print(results)
[78, 90, 61]
['fail', 'pass', 'pass', 'fail', 'pass']

The filter if at the end shortens the list; the if/else at the front keeps all five marks.

Solution 2

words = ["sky", "python", "loop", "map", "comprehension"]
lengths = {word: len(word) for word in words if len(word) > 3}
print(lengths)
{'python': 6, 'loop': 4, 'comprehension': 13}

The colon makes it a dictionary, and the if at the end drops “sky” and “map”.

Solution 3

groups = [["Ali", "Sara"], ["Omar", "Ali"], ["Sara", "Hina", "Ali"]]
names = {name for group in groups for name in group}
print(sorted(names))
print(len(names))
['Ali', 'Hina', 'Omar', 'Sara']
4

Two for clauses go through every name in every group, and the set keeps each name once.

Common mistakes

  • Putting else in the filter. [price for price in prices if price < 100 else 0] gives SyntaxError: invalid syntax. if ... else goes at the front.
  • Forgetting brackets around a tuple. [size, colour for ...] gives SyntaxError: did you forget parentheses around the comprehension target?.
  • Using the loop variable afterwards. The reference says comprehension names do not “leak” out. After [price + 50 for price in prices], print(price) gives NameError: name 'price' is not defined. Did you mean: 'prices'?. A plain for loop’s variable does still exist after the loop.
  • Using a comprehension only to print. Use a for loop instead.
  • Mixing up dict and set braces. {n: n * 2 for n in range(3)} is a dict; without the colon it is a set.

Frequently asked questions

How do you use if else in a list comprehension in Python?

Put the whole if ... else before the for: ["cheap" if p < 100 else "expensive" for p in prices]. This keeps every item and chooses a value for each. To drop items, use if alone after the for.

What is the difference between a list comprehension and a for loop?

Both go through items one by one. A comprehension always builds a new list, so it is best for “make a new list from an old one”. A for loop can do anything, such as printing or stopping early, so use it when the work is more than building one list.

How do you create a dictionary with a comprehension in Python?

Use curly braces with key: value before the for, for example {name: len(name) for name in names}. To build one from two lists, use zip(): {n: p for n, p in zip(names, prices)}. To change an existing dictionary, loop over .items().

Summary

  • [expression for item in items] builds a new list and leaves the old one alone.
  • if at the end filters; x if test else y at the front chooses a value.
  • {key: value for ...} makes a dict; {value for ...} makes a set.
  • Several for clauses run like nested loops, outer loop first.
  • Use a plain loop for printing or long logic, and a generator expression, such as sum(x for x in items), when you need the values only once.

Next lesson

Next: Lesson 22, Python Functions: def, return, Parameters and Docstrings.

Sources

Ihsan Ullah

Written & tested by Ihsan Ullah

Data analyst with 3 years of experience and a Bachelor's degree in Computer Science. I write clear, practical guides on data, SQL, Python and AI.

More about me →

Leave a comment

Your email address will not be published. Required fields are marked *