Lambda: Anonymous Functions
Lambda functions are small, anonymous functions defined with lambda instead of def. Useful for short throwaway functions โ especially as arguments to other functions.
# Syntax: lambda arguments: expression
square = lambda x: x ** 2
add = lambda a, b: a + b
greet = lambda name: f"Hello, {name}!"
print(square(5)) # 25
print(add(3, 4)) # 7
# Equivalent def functions
def square(x): return x ** 2PEP 8 Guidance
PEP 8 recommends against assigning lambda to a variable โ just use def. Lambda shines as an inline argument, not as a named function.
Lambda with sorted()
students = [
{"name": "Alice", "grade": 85},
{"name": "Bob", "grade": 92},
{"name": "Carol", "grade": 78},
]
# Sort by grade ascending
by_grade = sorted(students, key=lambda s: s["grade"])
# Sort by grade descending
by_grade_desc = sorted(students, key=lambda s: s["grade"], reverse=True)
# Sort strings case-insensitively
words = ["Banana", "apple", "Cherry", "fig"]
sorted(words, key=lambda w: w.lower())
# ['apple', 'Banana', 'Cherry', 'fig']
# Sort by string length, then alphabetically (multi-key)
sorted(words, key=lambda w: (len(w), w.lower()))
# Often you don't need lambda โ use operator module
from operator import itemgetter
sorted(students, key=itemgetter("grade"))map() and filter()
numbers = [1, 2, 3, 4, 5]
# map(func, iterable) โ apply function to each element
squares = list(map(lambda x: x**2, numbers))
# [1, 4, 9, 16, 25]
# filter(func, iterable) โ keep where function returns True
evens = list(filter(lambda x: x % 2 == 0, numbers))
# [2, 4]
# In modern Python, prefer comprehensions
squares = [x**2 for x in numbers]
evens = [x for x in numbers if x % 2 == 0]
# map/filter shine when using existing functions
words = ["hello", "world", "python"]
upper_words = list(map(str.upper, words)) # No lambda needed!
long_words = list(filter(lambda w: len(w) > 4, words))Higher-Order Functions
Functions that take functions as arguments or return functions. This is a core concept in functional programming and makes code highly reusable.
# Function that takes a function
def apply_twice(func, value):
return func(func(value))
def double(x):
return x * 2
apply_twice(double, 3) # 12 (double(double(3)) = double(6) = 12)
apply_twice(str.upper, "hello") # "HELLO" (already upper after first call)
# Function that returns a function (factory pattern)
def make_multiplier(n):
def multiplier(x):
return x * n
return multiplier
triple = make_multiplier(3)
quintuple = make_multiplier(5)
triple(7) # 21
quintuple(4) # 20
# Power of factories: configure behavior at creation time
def make_logger(prefix):
def log(message):
print(f"[{prefix}] {message}")
return log
info_log = make_logger("INFO")
error_log = make_logger("ERROR")
info_log("Server started") # [INFO] Server started
error_log("Connection failed") # [ERROR] Connection failedfunctools.reduce()
from functools import reduce
# reduce(func, iterable) โ combine all elements with func
product = reduce(lambda x, y: x * y, [1, 2, 3, 4, 5])
# 120 = 1*2*3*4*5 (apply repeatedly left to right)
# Flatten nested list
nested = [[1, 2], [3, 4], [5, 6]]
flat = reduce(lambda a, b: a + b, nested)
# [1, 2, 3, 4, 5, 6]
# Running maximum
data = [3, 1, 4, 1, 5, 9, 2, 6]
running_max = reduce(lambda acc, x: acc + [max(acc[-1], x)], data[1:], [data[0]])
# [3, 3, 4, 4, 5, 9, 9, 9]functools.partial()
from functools import partial
def power(base, exponent):
return base ** exponent
# Pre-fill some arguments
square = partial(power, exponent=2)
cube = partial(power, exponent=3)
square(5) # 25
cube(3) # 27
# Practical: log levels
import logging
log_error = partial(print, "[ERROR]")
log_info = partial(print, "[INFO]")
log_error("Something went wrong") # [ERROR] Something went wrongKey Takeaways
- Lambda for inline functions: best as sort keys, map/filter args
- Comprehensions over map/filter: more readable in most cases
- Functions are first-class objects: pass them around, return them
- partial(): create specialized versions of functions with pre-set arguments
- Factory functions: return configured functions for reusable behavior
Practice Exercises
- Sort a list of
(name, score)tuples by score descending, then by name alphabetically on ties. - Write a higher-order function
compose(f, g)that returns a function equivalent tof(g(x)). - Use
functools.partialto create adouble()andtriple()function from a genericmultiply(a, b). - Write a
pipeline(*funcs)that takes any number of functions and applies them left-to-right to an input value.