Start learning free

LESSON 266 OF 673 · TUPLES, SORTING & BUILT-INS

List Comprehensions in Python

Lesson

TL ; DR:

A list comprehension builds a new list from another list, in one line. It can change every item, keep only some items, or both.


nums = [1, 2, 3, 4]

squares = [n * n for n in nums]
print(squares)                         # [1, 4, 9, 16]

evens = [n for n in nums if n % 2 == 0]
print(evens)                           # [2, 4]

big = [n * 10 for n in nums if n > 2]
print(big)                             # [30, 40]


Full lesson:

You often build a new list from an old one. You already know how to do it with a loop:

squares = []
for n in nums:
    squares.append(n * n)

A list comprehension does the same in one line:

squares = [n * n for n in nums]

It reads like a sentence: take n * n for each n in nums. The square brackets collect the results in a new list.

The part before for is what goes in the new list. Every item changes in the same way. Other languages call this a map.

An if at the end keeps only some items. Other languages call this a filter. Here each even n goes in as it is:

evens = [n for n in nums if n % 2 == 0]

You can do both at once. The if picks the items, then the front part changes them:

big = [n * 10 for n in nums if n > 2]    # [30, 40]

A comprehension always makes a new list. The old list, nums, stays as it was.

Watch out: use square brackets. With round brackets, Python doesn't make a list.


Your task

A theater keeps the price of one ticket for each show in prices. Build doubled with a list comprehension: the price of two tickets for each show.

A quiz keeps its scores in scores. A score of 50 or more passes. Build passed with a list comprehension too: only the passing scores.

The code already prints both lists, one value per line.

Expected output:

Two tickets cost 24
Two tickets cost 16
Two tickets cost 30
72 passed
50 passed
90 passed
STEP 1 OF 2
    Ctrl + Enter to check