Python course / Working Python
Comprehensions
Write the list-building loop you already know as one expression, and recognise when not to. A comprehension stops being clever the moment a reader has to go through it twice.
- list, dict, set
- filtering
- nested fors
- lambda
- key functions
- generator expressions
- any and all
Runs in your browser. Start straight away; create an account when you want your progress kept.
rows = [("tea", 350), ("jam", 225), ("oats", 180), ("honey", 400)]
cheap = [name for name, pence in rows if pence < 300]
prices = {name: pence / 100 for name, pence in rows}
print("cheap:", cheap)
print("tea in pounds:", prices["tea"])
print("total pence:", sum(pence for _, pence in rows))
print("any at four pounds or more:", any(pence >= 400 for _, pence in rows))
cheap: ['jam', 'oats'] tea in pounds: 3.5 total pence: 1155 any at four pounds or more: True
What you will learn
- Write the list-building loop you already know as one expression.
- Keep only the items you want, and know what runs first.
- Recognise a comprehension that has stopped being clear, and turn it back into a loop.
- Build a dictionary from another collection in one expression.
- Hand values to a function one at a time, without building a list first.
- Ask whether some or every item passes a test, and stop as soon as the answer is known.
The lessons in this module
- From loop to comprehension
- Filtering
- Changing and choosing at once
- When not to use one
- Dict comprehensions
- Set comprehensions
- Two fors in one comprehension
- Lists of lists
- Choosing a value, or choosing an item
- lambda
- key functions
- map and filter
- Generator expressions
- any and all
- Where the loop variable goes
- The walrus in a comprehension
- The supplier's list
- Module review: the market stall
Ready when you are
Previous: Modules and imports. Next: Type hints. All modules are on the course page.