PyComplete Python Course
Intermediate 45 min

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.

Syntax
double = lambda x: x * 2
list(map(double, numbers))
list(filter(lambda x: x > 0, numbers))

Examples

lambda basics Very Easy

lambda basics
square = lambda x: x * x
print(square(5))
Output25

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

map()
numbers = [1, 2, 3, 4]
doubled = list(map(lambda x: x * 2, numbers))
print(doubled)
Output[2, 4, 6, 8]

map(function, iterable) applies function to every item and returns an iterator, which list() turns into a real list.

filter() Easy

filter()
numbers = [1, -2, 3, -4, 5]
positives = list(filter(lambda x: x > 0, numbers))
print(positives)
Output[1, 3, 5]

filter(function, iterable) keeps only the items where function returns True.

enumerate() and zip() Intermediate

enumerate() and zip()
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}")
Output1 Ada 2 Sam 3 Lee Ada: 92 Sam: 85 Lee: 78

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

any(), all(), and sorted with a key
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))
OutputTrue True [91, 82, 55, 40]

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

map(lambda x: x*2, ...)12243648
map() and filter() both walk through a sequence applying a small function to each item.
πŸ’‘ 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

βœ— Common mistake 1

map() and filter() return lazy iterators in Python 3, not lists β€” printing one directly shows a memory reference, not the values.

βœ— Avoid this
This raises prints something like <map object at 0x...> instead of the values
result = map(lambda x: x*2, [1, 2, 3])
print(result)
βœ“ Better approach
Fixed
result = list(map(lambda x: x*2, [1, 2, 3]))
print(result)
βœ“ Best practices
  • 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

Given this code
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
Python
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?

A variable
A small anonymous function
A list comprehension
A loop
lambda defines a small, unnamed, inline function.

2. What does filter() keep from a sequence?

Every item
Only items where the function returns True
Only the first item
Only duplicates
filter() keeps items that pass the given test function.

3. What does zip(names, scores) produce?

A single merged list
Pairs combining corresponding items from each sequence
A dictionary
An error if lengths differ
zip() pairs items positionally from each iterable it's given.

4. Why must you often wrap map() in list()?

map() returns a string
map() returns a lazy iterator, not a list
It's required syntax
It isn't necessary at all
map() and filter() are lazy β€” list() forces them to produce their values.

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.

Related lessons

Saved privately in your browser β€” no account needed.