Skip to content
skillbld
Day 13 of 14 30 minComprehensionsGeneratorsenumerate / zip

Write code the way experienced Python developers do. Comprehensions, enumerate and zip, generators, lambdas and the idioms that make Python short and readable.

By the end of today you can

  • Build lists, dicts and sets with comprehensions
  • Loop over pairs with zip() and positions with enumerate()
  • Use generators to process data lazily
  • Sort and filter with key functions and lambdas
  • Recognise common Pythonic idioms

You can already solve problems in Python. Today is about solving them elegantly. "Pythonic" code uses the language's strengths to be short, clear and fast to read.

Mind map · click a dot to fold, drag to pan

List comprehensions

A comprehension builds a new list from an existing sequence in one readable line:

Sketch
Anatomy of [n * n for n in numbers if n > 0]: the expression n * n says what to put in, the for clause says where items come from, and the optional if clause says which items to keep.
main.py · editable
Output
Press Run to execute this code.
main.py · editable
Output
Press Run to execute this code.

Dict and set comprehensions

main.py · editable
Output
Press Run to execute this code.

enumerate() and zip()

main.py · editable
Output
Press Run to execute this code.
Sketch
Names Ada, Grace and Linus are paired with scores 92, 88 and 75 by position, producing the tuples (Ada, 92), (Grace, 88) and (Linus, 75).

Generators: one item at a time

Square brackets build the whole list in memory. Parentheses make a generator that produces values only when they're needed:

main.py · editable
Output
Press Run to execute this code.

Functions as values: key and lambda

Many functions take a key function that decides how to compare items. A lambda is a tiny, unnamed function written inline:

main.py · editable
Output
Press Run to execute this code.

Small idioms with big impact

main.py · editable
Output
Press Run to execute this code.
Instead ofWrite
for i in range(len(xs)): then xs[i]for i, x in enumerate(xs):
A loop that appends to a listA list comprehension
if len(items) > 0:if items:
tmp = a; a = b; b = tmpa, b = b, a
Building a list just to sum itsum(x for x in xs)

Recap

  • Comprehensions build lists, dicts and sets in one readable line: [expr for x in xs if cond].
  • enumerate() gives positions; zip() walks sequences side by side.
  • Generators and yield produce values lazily, saving memory.
  • key= functions and lambda customise sorting, max and min.
  • Pythonic code is clear first and short second.

Knowledge check

Test what you learned

5 questions · pick an answer to see if you're right

0/5
  1. 1

    What does [n * n for n in range(4)] produce?

  2. 2

    What does [n for n in range(10) if n % 3 == 0] produce?

  3. 3

    What does list(zip(["a", "b", "c"], [1, 2])) return?

  4. 4

    What is the main advantage of a generator expression like (x * 2 for x in data)?

  5. 5

    sorted(words, key=len) sorts the words by...

Finished today's lesson?