🎓 A1Learner
🔍

Python List Comprehension

A list comprehension is a one-line way to build a new list. A for loop with append() builds a list one item at a time.

Build a list with a loop

A loop builds the list one item at a time.

nums = [1, 2, 3, 4]
squares = []
for n in nums:
    squares.append(n * n)
print(squares)

A shorter way to build a list

Read it as: square each n in nums.

nums = [1, 2, 3, 4]
squares = [n * n for n in nums]
print(squares)

Add a filter with if

The if part keeps only the items you want.

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

Change each item as you go

The first part can be any expression.

words = ["cat", "dog", "fox"]
loud = [w.upper() for w in words]
print(loud)

The same job as a loop

Both forms below build the same list.

nums = [1, 2, 3]
loop_result = []
for n in nums:
    loop_result.append(n + 10)
comp_result = [n + 10 for n in nums]
print(loop_result)
print(comp_result)

Example

squares_loop = []
for n in range(1, 21):
    if n % 2 == 0:
        squares_loop.append(n * n)
print(squares_loop)
squares_comp = [n * n for n in range(1, 21) if n % 2 == 0]
print(squares_comp)
print(squares_loop == squares_comp)

Key points

  • List comprehension: a one-line way to build a new list
  • Pattern: [expr for item in list] runs the expr for each item
  • Use if at the end to keep only items that pass a test
  • Use a plain loop when the one-line form gets hard to read
  • It never changes the list you read from.

In this example, the loop visits each number from 1 to 20. The if test keeps only the even numbers. Each kept number is squared and added with append(). The comprehension then does the same job in one line. It squares each even number from the same range. Both lists print the same values. The last line checks them with == and prints True.

Note

A comprehension always builds a new list.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

What does [n * 2 for n in [1, 2, 3] if n > 1] give?