ShareYourGroupShareYourGroupPython

Lesson 20 of 21 · about 7 minutes with the exercises

List comprehensions

You have often built a list like this: start with an empty list, loop over something, append to the list. A list comprehension writes the same thing in one line. It is one of the features that makes Python code short and readable, and you will see it in almost every program written by experienced people.

From loop to comprehension

Here is the long way and the short way, side by side.

squares = []
for n in range(1, 6):
    squares.append(n * n)
print(squares)

squares = [n * n for n in range(1, 6)]
print(squares)

Output

[1, 4, 9, 16, 25]
[1, 4, 9, 16, 25]

The comprehension has the pieces of the loop in a different order:

Read it as: "n times n, for each n in the range 1 to 5".

Changing every item

prices = [100, 250, 80]
with_gst = [p * 1.18 for p in prices]
print(with_gst)

names = ["asha", "ravi", "meena"]
print([name.title() for name in names])
print([len(name) for name in names])

Output

[118.0, 295.0, 94.39999999999999]
['Asha', 'Ravi', 'Meena']
[4, 4, 5]

The original list is not touched. A comprehension always builds a new list.

Keeping only some items

Add an if at the end to filter. Only items that pass the test go in.

marks = [78, 45, 91, 60, 33, 88]
passed = [m for m in marks if m >= 60]
print(passed)

words = ["tea", "coffee", "milk", "buttermilk"]
print([w for w in words if len(w) > 4])

Output

[78, 91, 60, 88]
['coffee', 'buttermilk']

This is the safe way to "remove" items from a list, which you were warned not to do inside a plain for loop: build a new list of the ones you want to keep.

Changing and filtering together

numbers = [3, 8, 12, 7, 20]
print([n * 10 for n in numbers if n % 2 == 0])

Output

[80, 120, 200]

The filter runs first, then the expression at the front is applied to what is left.

Choosing between two results

To put a different value in depending on a test, without dropping anything, the if and else go at the front.

marks = [78, 25, 91, 30]
print(["pass" if m >= 33 else "fail" for m in marks])

Output

['pass', 'fail', 'pass', 'fail']

So an if at the end filters, and an if ... else at the front chooses. Mixing up the two positions is the usual mistake.

Working with text

A comprehension can loop over a string, or over the pieces from split.

sentence = "the cat sat on the mat"
print([w.upper() for w in sentence.split()])
print([ch for ch in "programming" if ch in "aeiou"])

text = "12 7 30 5"
numbers = [int(piece) for piece in text.split()]
print(numbers, sum(numbers))

Output

['THE', 'CAT', 'SAT', 'ON', 'THE', 'MAT']
['o', 'a', 'i']
[12, 7, 30, 5] 54

The last example is the short form of the conversion loop from lesson 12.

Feeding a function directly

When the list is only needed to be added up, counted or searched, you can drop the square brackets and write the comprehension straight inside the function call.

marks = [78, 45, 91, 60]
print(sum(m for m in marks if m >= 60))
print(max(len(w) for w in ["tea", "coffee", "milk"]))
print(any(m < 33 for m in marks))
print(all(m >= 33 for m in marks))

Output

229
6
False
True

any is true if at least one item passes. all is true only if every item does.

Dictionary and set comprehensions

Curly brackets with a key: value pair make a dictionary. Curly brackets with a single value make a set.

names = ["Asha", "Ravi", "Meena"]
lengths = {name: len(name) for name in names}
print(lengths)

prices = {"tea": 10, "lassi": 40, "samosa": 15}
print({item: price for item, price in prices.items() if price < 20})

print(sorted({len(name) for name in names}))

Output

{'Asha': 4, 'Ravi': 4, 'Meena': 5}
{'tea': 10, 'samosa': 15}
[4, 5]

Two loops in one comprehension

A comprehension can hold two for parts. The first is the outer loop.

pairs = [(shirt, size) for shirt in ["red", "blue"] for size in ["S", "M"]]
print(pairs)

Output

[('red', 'S'), ('red', 'M'), ('blue', 'S'), ('blue', 'M')]

When not to use one

A comprehension should fit on one line and be clear at a glance. If you need two conditions and a nested loop, write an ordinary loop instead. Short is good only while it stays readable. A simple test: can you say aloud what it does in one breath?

Also, a comprehension is for making a list. Do not use one just to call print many times. That is a job for a plain loop.

Try it yourself

Exercise 1. Make a list of the cubes of the numbers 1 to 6.

Show one answer
print([n ** 3 for n in range(1, 7)])

Output

[1, 8, 27, 64, 125, 216]

Exercise 2. From temps = [31, 38, 29, 41, 36], make a list of the temperatures above 35.

Show one answer
temps = [31, 38, 29, 41, 36]
print([t for t in temps if t > 35])

Output

[38, 41, 36]

Exercise 3. From the sentence "learning python step by step", make a list of the first letter of each word, in capitals.

Show one answer
sentence = "learning python step by step"
print([w[0].upper() for w in sentence.split()])

Output

['L', 'P', 'S', 'B', 'S']

Examples on this page were run with Python 3.14 on 12 November 2026. The output shown is the real output.

This is an independent learning site. It is not connected with or approved by the Python Software Foundation. "Python" is a trademark of the Python Software Foundation and is used here only to name the language.