Python · Module 05: Functions & ScopeTutorial 15 of 30
All Tutorials·~1.5 hrs

5.3 Lambdas, map/filter, sorted(key=...) & Recursion

Write quick anonymous lambda functions for custom sorting, compare map/filter with comprehensions, and visualize how recursion uses the Call Stack.

01 Intuition: Plain-English mental model
02 Visuals: Step-by-step diagrams
03 Practice: Clean examples & tradeoffs

1. Lambda Functions (1-Line Disposable Functions)

Sometimes you need a tiny throwaway function for 2 seconds — for example, telling sorted() which field to sort by. A lambda is a single-expression anonymous function:

PYTHON
# Normal function
def square(x):
    return x * x

# Equivalent 1-line lambda
square = lambda x: x * x

The #1 Real-World Use of lambda: Custom Sorting with key=!

PYTHON
students = [("Aarav", 88), ("Riya", 96), ("Kabir", 79)]

# Sort by score (index 1), highest first!
ranked = sorted(students, key=lambda s: s[1], reverse=True)
print(ranked)
# [('Riya', 96), ('Aarav', 88), ('Kabir', 79)]

(Style tip: Never assign f = lambda x: ... to a permanent variable — PEP 8 says use def for named functions and save lambda for inline callbacks like sorted(key=...)!)


2. map() & filter() vs. List Comprehensions

Python supports functional tools map() (transform every item) and filter() (keep matching items), both of which return lazy iterators:

PYTHON
nums = [1, 2, 3, 4, 5]

# Functional style (map + filter)
evens_doubled = list(map(lambda x: x * 2, filter(lambda x: x % 2 == 0, nums)))

# Pythonic List Comprehension (Usually much cleaner!)
evens_doubled = [x * 2 for x in nums if x % 2 == 0]
# Both produce: [4, 8]

3. Recursion: A Function That Calls Itself

Recursion is when a function solves a big problem by breaking it into a smaller copy of the exact same problem — like opening nested Russian Matryoshka dolls until you reach the tiniest solid doll inside.

Every recursive function MUST have two ingredients:

  1. Base Case: The stopping condition (otherwise Python crashes with RecursionError at ~1,000 calls!).
  2. Recursive Step: Calls itself with a smaller input moving toward the base case.
Visual: Recursion Call Stack for `factorial(3)` — Winding Down & Returning Back Up
factorial(3)3 * factorial(2)returns 6 ✓factorial(2)2 * factorial(1)returns 2factorial(1)BASE CASE!returns 1Every recursive function needs TWO parts: a Base Case (stops recursion) and a Recursive Step (shrinks problem).
PYTHON
def factorial(n):
    if n <= 1:               # 1) Base Case — stops recursion!
        return 1
    return n * factorial(n - 1)  # 2) Recursive Step — shrinks n toward 1

print(factorial(5))          # 120 (5 × 4 × 3 × 2 × 1)

4. Interactive Trace: Custom Sorting with lambda

Tracing Custom Sorting & Top-Score Lookup
Interactive Line-by-Line Execution Trace · Step 1 of 4
1→words = ["python", "hi", "code", "a"]
2by_len = sorted(words, key=lambda w: len(w))
3longest = max(words, key=lambda w: len(w))
4print(by_len, "->", longest)
Variables in Memory
words["python", "hi", "code", "a"]list
Console Output
(nothing printed yet)
What just happened: Default sorted(words) would sort alphabetically (['a', 'code', 'hi', 'python']).

Quick Quiz: Module 5.3 — Lambdas & Recursion

Q1.What happens if a recursive function forgets its Base Case?
Q2.How do you sort `pairs = [(1, 9), (2, 3), (4, 1)]` by the SECOND element?
Q3.What does `(lambda x, y: x + y)(3, 4)` return?

Keep Exploring: Related Lessons & Tools

All Courses →