LevelJar Sign in

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

Start this module

Runs in your browser. Start straight away; create an account when you want your progress kept.

filter, transform, summarise
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

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

Start this module

Previous: Modules and imports. Next: Type hints. All modules are on the course page.