×

python · level 3 · unit 1 · lesson 1

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

A builds a whole list in one line.

You have written this loop many times: make an empty list, loop, append. A comprehension says the same thing in one line: [price / 100 for price in prices]. Read it aloud as "price divided by 100, for each price in prices".

Add an if on the end to , so only the items that pass the test make it in. The result is always a brand new list, and the old one is left untouched.

Use a comprehension when each new item comes from one old item. If the loop body grows past one idea, a normal loop reads better.

prices = [250, 1200, 480, 999]
in_pounds = [price / 100 for price in prices]
cheap = [price for price in prices if price < 500]
print(in_pounds)
print(cheap)

Square brackets around a comprehension always give you a list.