Phase: 4. Functions | Estimated time: 1.5 hours | Milestone Project: No
- Module 031 (Functions: Basics)
- Module 032 (Function Arguments)
By the end of this module, you will be able to:
- Write lambda functions with the
lambdakeyword - Know when lambdas are appropriate (short callbacks)
- Understand the limitations of lambdas (single expression only)
- Use lambdas with
sorted()andkey= - Use lambdas with
map()andfilter()briefly
Lambdas allow you to write small, throwaway functions inline without a def statement. They are essential for callbacks, sorting with custom keys, and functional programming patterns.
lambda arguments: expressionA lambda is a function without a name that evaluates a single expression:
square = lambda x: x ** 2
print(square(5)) # 25This is equivalent to:
def square(x):
return x ** 2Use lambdas for short, simple operations passed directly as arguments:
- Sorting with custom keys
- Callbacks for GUI/event handling
- Short transformations with
map()andfilter()
- Single expression only — no statements, no assignments, no loops.
- No docstrings — hard to self-document.
- Harder to debug — no name in tracebacks.
students = [("Alice", 85), ("Bob", 72), ("Charlie", 90)]
students.sort(key=lambda s: s[1]) # sort by grade
print(students) # [('Bob', 72), ('Alice', 85), ('Charlie', 90)]nums = [1, 2, 3, 4, 5]
doubled = list(map(lambda x: x * 2, nums))
evens = list(filter(lambda x: x % 2 == 0, nums))max_val = lambda a, b: a if a > b else b
print(max_val(10, 20)) # 20- Trying to use statements:
lambda x: return x + 1is invalid —returnis a statement. - Overusing lambdas: If it's more than one expression, use
def. - Capturing loop variables: Lambdas in loops capture by reference, not by value.
- Write a lambda that returns the absolute value and test it.
- Sort a list of strings by their length using
sorted()withkey=lambda. - Use
map()with a lambda to convert temperatures from Celsius to Fahrenheit. - Use
filter()with a lambda to keep only positive numbers from a list.
- Lambda:
lambda args: expression— anonymous, inline, single expression. - Best for short callbacks (sorting, mapping, filtering).
- Cannot contain statements (no
return,if/elseblocks, loops). - If it's complex, use
definstead.
Continue to Module 035: Recursion.