Velamuvi AIAcademy

Lesson 1 of 16 · Pythonic Code

List Comprehensions

Learn Python list comprehensions: build new lists in one readable line, filter items with if, transform data and know when a normal loop is clearer.

  • 9 min read
  • Intermediate
  • Reviewed
In this lesson you will learn
  • How to build a new list from an existing one in a single line
  • How to filter items with an if condition
  • How to choose between two values with if and else
  • When a normal for loop is the better choice

The loop you write all the time

Very often you take a list, do something to every item, and collect the results in a new list. In Python for Beginners you wrote it like this:

Try it yourselfPython
prices = [10, 25, 40]

with_tax = []
for price in prices:
    with_tax.append(price * 1.2)

print(with_tax)

Four lines for a simple idea: "the price with tax, for each price". Python has a shorter way to say exactly that.

Your first list comprehension

A list comprehension builds a new list in one expression.

Try it yourselfPython
prices = [10, 25, 40]

with_tax = [price * 1.2 for price in prices]

print(with_tax)

Read it from the middle out:

  • for price in prices goes through the list, one item at a time.
  • price * 1.2 is what to put in the new list for each item.
  • The square brackets around everything collect the results into a list.

The result is the same as the loop. The comprehension is shorter, and once you are used to it, it reads almost like English: "price times 1.2, for every price in prices".

More examples

The part before for can be any expression: a calculation, a method call or a function call.

Try it yourselfPython
names = ["ada", "grace", "alan"]
words = ["data", "model", "training"]

print([name.title() for name in names])
print([len(word) for word in words])
print([n * n for n in range(1, 6)])

Keeping only some items

Add if at the end to keep only the items that pass a test. This is called filtering.

Try it yourselfPython
scores = [92, 45, 78, 61, 88, 39]

passed = [score for score in scores if score >= 60]

print(passed)

You can filter and transform in the same comprehension.

Try it yourselfPython
words = ["AI", "is", "changing", "how", "we", "learn"]

long_words = [word.upper() for word in words if len(word) > 3]

print(long_words)

Choosing between two values

Sometimes you want to keep every item but change it in one of two ways. Put if ... else before the for.

Try it yourselfPython
scores = [92, 45, 78, 39]

results = ["pass" if score >= 60 else "fail" for score in scores]

print(results)

The position tells you which job the if is doing:

WhereMeaningExample
if at the endKeep only some items[s for s in scores if s >= 60]
if ... else at the startKeep every item, choose its value["pass" if s >= 60 else "fail" for s in scores]

Working with a list of dictionaries

Comprehensions are perfect for pulling one field out of a list of records.

Try it yourselfPython
students = [
    {"name": "Ada", "score": 92},
    {"name": "Grace", "score": 85},
    {"name": "Alan", "score": 58},
]

names = [student["name"] for student in students]
top = [student["name"] for student in students if student["score"] >= 80]

print(names)
print(top)

Nested loops in a comprehension

You can write two for parts. They run in the same order as nested loops would.

Try it yourselfPython
sizes = ["S", "M"]
colours = ["red", "blue"]

products = [f"{colour}-{size}" for colour in colours for size in sizes]

print(products)

This is the same as a for colour loop with a for size loop inside it. Two for parts are fine. More than that becomes hard to read.

When not to use a comprehension

A comprehension is for building a list. If you are printing, saving files or doing several steps per item, a normal loop is clearer.

# Hard to read: too much in one line
report = [f"{s['name']}: {'pass' if s['score'] >= 60 else 'fail'} ({s['score'] / 100:.0%})" for s in students if s["name"]]

# Clearer as a loop
for student in students:
    result = "pass" if student["score"] >= 60 else "fail"
    print(f"{student['name']}: {result}")

A good rule: if a comprehension does not fit comfortably on one line, or you have to read it twice, write a loop.

Common mistakes

Practice exercise

Use one list comprehension to keep the warm days and convert them to Fahrenheit.

Your solutionPython
temperatures = [18, 25, 31, 12, 27]

# Make a new list called warm that keeps only temperatures above 20,
# converted to Fahrenheit with: c * 9 / 5 + 32
# Then print it. Output must be exactly:
# [77.0, 87.8, 80.6]
Knowledge check

What does [n * 2 for n in [1, 2, 3] if n != 2] produce?

Summary

  • [expression for item in items] builds a new list in one line.
  • Add if condition at the end to keep only some items.
  • Put value_a if condition else value_b at the start to choose each item's value.
  • Use a normal loop when the work does not fit comfortably on one line, or when you are not building a list.

Next: the same idea for dictionaries and sets.

Finished reading? Tick it off to track your progress.