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.
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:
# 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=!
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:
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:
- Base Case: The stopping condition (otherwise Python crashes with
RecursionErrorat ~1,000 calls!). - Recursive Step: Calls itself with a smaller input moving toward the base case.
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
Quick Quiz: Module 5.3 — Lambdas & Recursion
Keep Exploring: Related Lessons & Tools
All Courses →Compare two versions of text, source code, config files, or JSON payloads side-by-side using exact LCS diffing with recursive JSON key sorting and patch export.
Convert Unix epoch seconds/milliseconds to ISO-8601 and local timezones, and bulk-generate UUID v4, time-ordered UUID v7, and sortable ULIDs.