Leveling Up: Comprehensions and Lambdas
You now know enough Python to build real programs. This lesson levels you up with two tools that make code shorter and more "Pythonic": comprehensions and lambda functions. They are common in professional code, so recognizing them matters.
What You'll Learn
- List comprehensions to build and filter lists
- Dict and set comprehensions
- Lambda functions for quick one-line logic
- Using lambdas with
sorted,map, andfilter
List Comprehensions
A comprehension builds a list in one line. Compare the loop to the comprehension:
Loading Python Playground...
The pattern is [expression for item in iterable].
Loading Python Exercise...
Filtering With if
Add an if at the end to keep only items that match:
Loading Python Playground...
Loading Python Exercise...
Dict and Set Comprehensions
The same idea builds dictionaries and sets:
Loading Python Playground...
Lambda Functions
A lambda is a tiny anonymous function written in one line: lambda args: expression. It is handy when you need a quick function to pass to another function:
Loading Python Playground...
Lambdas With sorted, map, and filter
This is where lambdas earn their keep. Give sorted a key to sort by something custom, or transform and filter whole lists:
Loading Python Playground...
Loading Python Exercise...
When to Use Which
- Reach for a comprehension to build or filter a collection
- Reach for a lambda for a short throwaway function passed to
sorted,map, orfilter - For anything longer or reused, write a normal
deffunction
Key Takeaways
- List comprehension:
[expr for item in iterable] - Filter by adding
if conditionat the end - Dict and set comprehensions use
{ } lambda args: expressionis a one-line function- Lambdas pair naturally with
sorted,map, andfilter
Quiz
Question 1 of 425% Complete
0 of 4 questions answered

