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.
List comprehensions
A comprehension builds a new list from an existing sequence in one readable line:
Dict and set comprehensions
enumerate() and zip()
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:
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:
Small idioms with big impact
| Instead of | Write |
|---|---|
for i in range(len(xs)): then xs[i] | for i, x in enumerate(xs): |
| A loop that appends to a list | A list comprehension |
if len(items) > 0: | if items: |
tmp = a; a = b; b = tmp | a, b = b, a |
| Building a list just to sum it | sum(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
yieldproduce values lazily, saving memory. key=functions andlambdacustomise sorting,maxandmin.- 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
- 1
What does [n * n for n in range(4)] produce?
- 2
What does [n for n in range(10) if n % 3 == 0] produce?
- 3
What does list(zip(["a", "b", "c"], [1, 2])) return?
- 4
What is the main advantage of a generator expression like (x * 2 for x in data)?
- 5
sorted(words, key=len) sorts the words by...
Finished today's lesson?