Module 11 β Functional Programming & Advanced Functions
Lambda expressions, map/filter, and treating functions as ordinary values.
Prerequisite: Module 09 β Sets & Comprehensions
After this lesson, you will be able to
- Write small anonymous functions with lambda
- Transform and filter sequences with map() and filter()
- Pair up sequences with zip() and track positions with enumerate()
- Use any() and all() and a custom sort key
Concept & Syntax
In Python, functions are values β you can store one in a variable, pass it into another function, or return
it from a function, exactly like a number or a string. Functional programming leans into that:
instead of writing a loop to transform every item in a list, you hand a small function to a tool like
map() and let it apply that function everywhere.
lambda lets you write a tiny, unnamed function inline, for exactly the situations where defining
a whole separate function with def would be overkill.
double = lambda x: x * 2
list(map(double, numbers))
list(filter(lambda x: x > 0, numbers))Examples
lambda basics Very Easy
square = lambda x: x * x
print(square(5))lambda x: x * x is an unnamed function equivalent to def square(x): return x * x β assigned to a name here for clarity.
map() Easy
numbers = [1, 2, 3, 4]
doubled = list(map(lambda x: x * 2, numbers))
print(doubled)map(function, iterable) applies function to every item and returns an iterator, which list() turns into a real list.
filter() Easy
numbers = [1, -2, 3, -4, 5]
positives = list(filter(lambda x: x > 0, numbers))
print(positives)filter(function, iterable) keeps only the items where function returns True.
enumerate() and zip() Intermediate
names = ["Ada", "Sam", "Lee"]
scores = [92, 85, 78]
for i, name in enumerate(names, start=1):
print(i, name)
for name, score in zip(names, scores):
print(f"{name}: {score}")enumerate() pairs each item with its position; zip() walks two (or more) sequences together, item by item.
any(), all(), and sorted with a key Real World
scores = [55, 82, 40, 91]
print(any(s > 90 for s in scores))
print(all(s > 30 for s in scores))
print(sorted(scores, key=lambda s: -s))any() is True if at least one item satisfies the condition; all() requires every item to. sorted(..., key=...) controls the sort order using a custom rule.
Visual Explanation
π‘ Why does this work?
Read the concept explanation above again slowly, line by line β every keyword there maps directly onto a line of code in the examples. If it still doesn't click, re-run the traced example (if this lesson has one) one step at a time.
π What happens internally? (advanced)
Under the hood, Python compiles your source into bytecode and runs it on a virtual machine (the CPython interpreter). Variables are names in a namespace dictionary pointing at objects in memory β which is exactly what the memory panel in the tracer above is showing you.
Common Mistakes
map() and filter() return lazy iterators in Python 3, not lists β printing one directly shows a memory reference, not the values.
result = map(lambda x: x*2, [1, 2, 3])
print(result)result = list(map(lambda x: x*2, [1, 2, 3]))
print(result)- Prefer a list comprehension over map()/filter() when it reads more clearly β both approaches are valid and idiomatic Python.
- Keep lambdas to one simple expression; use a regular def function if the logic grows.
- Wrap map()/filter() results in list() (or tuple()/set()) when you need to use them more than once.
Exercise & Challenge
Exercise 1 β Predict the output
nums = [10, 15, 20, 25]
result = list(filter(lambda n: n % 10 == 0, nums))
print(result)What does this print?
π Challenge
Given a list of dictionaries representing products (each with 'name' and 'price'), use sorted() with a lambda key to print them from cheapest to most expensive.
- Use sorted() with key=lambda
- Sort by the 'price' field
- Print each product's name and price on its own line
π‘ Need a hint?
key=lambda p: p["price"]
π Show a sample solution
products = [{"name": "Mouse", "price": 25}, {"name": "Keyboard", "price": 60}, {"name": "Cable", "price": 8}]
for p in sorted(products, key=lambda p: p["price"]):
print(p["name"], p["price"])Quiz
Answer every question, then submit to see your score and explanations.
1. What does lambda x: x * 2 create?
2. What does filter() keep from a sequence?
3. What does zip(names, scores) produce?
4. Why must you often wrap map() in list()?
Summary
- Functions are values in Python β they can be passed around like any other data.
- lambda creates small, unnamed functions for one-off use.
- map() transforms every item; filter() keeps only matching items.
- enumerate(), zip(), any(), and all() are common companions when working with sequences.