python · level 3 · unit 1 · lesson 1
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Some orders are empty. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
orders = [("tea", 3), ("cake", 0), ("scone", 2)]
wanted = [f"{qty} x {item}" for item, qty in orders if qty > 0]
print(wanted)
your turn
Your turn. Tidy up a list of email addresses.
In the first blank, strip the spaces from email and make it lower case. In the second, keep only addresses that are not empty once stripped.
fix it
The prices should double, but something odd appears.
- Look at what goes into each slot of the new list. Is it one price or the whole list?
- The left part uses
prices, the whole list, instead of the loop variable. - Change
prices * 2toprice * 2on line 2, then run.
nailed it
you can build lists in one line. :D
[expression for item in items]builds a new list.- An
ifon the end keeps only the matching items. - Use a normal loop when the body needs more than one idea.
new words in your collection
- comprehension
- filter
This lesson isn’t saved. A free account remembers every lesson you finish.