← Python Basics

Chapter 8

Comprehensions and built-ins

Comprehensions build a list, set or dict in one line: a loop, and maybe a test, inside brackets. Python also ships with built-in functions that save you writing loops at all: sum(), sorted(), max(), enumerate() and zip(). This chapter covers both, so you can read the short, tidy code experienced Python programmers write, and spot when len() is given something with no length.

12 cards

See the 12 cards
  1. What does this list comprehension print?[0, 2, 4]
  2. What does the if in this list keep?[0, 3, 6]
  3. What does this dict comprehension print?{'hi': 2, 'sea': 3}
  4. What does sum() print for this list?10
  5. What does sorted() print with reverse=True?[3, 2, 1]
  6. What does enumerate() pair each letter with?[(0, 'a'), (1, 'b')]
  7. What does zip() make of two lists?[(1, 'a'), (2, 'b')]
  8. What does max() with key=len print?banana
  9. Fill the blank in this list comprehensionfor
  10. What's wrong here: len() of a number?TypeError
  11. Built-in that pairs items from two listszip
  12. Built-in that gives each item with its positionenumerate

Image credits

  • What does this list comprehension print?: Brain Zap, CC0 1.0 Source
  • What does the if in this list keep?: Brain Zap, CC0 1.0 Source
  • What does this dict comprehension print?: Brain Zap, CC0 1.0 Source
  • What does sum() print for this list?: Brain Zap, CC0 1.0 Source
  • What does sorted() print with reverse=True?: Brain Zap, CC0 1.0 Source
  • What does enumerate() pair each letter with?: Brain Zap, CC0 1.0 Source
  • What does zip() make of two lists?: Brain Zap, CC0 1.0 Source
  • What does max() with key=len print?: Brain Zap, CC0 1.0 Source
  • Fill the blank in this list comprehension: Brain Zap, CC0 1.0 Source
  • What's wrong here: len() of a number?: Brain Zap, CC0 1.0 Source