A lambda is a small, unnamed function limited to a single expression — Python's equivalent of PHP's arrow functions (fn).
double = lambda n: n * 2
print(double(5)) # 10
# Equivalent to:
def double(n):
return n * 2A lambda can take multiple arguments, but its body is always exactly one expression — no statements, no multiple lines.
Lambdas are rarely assigned to a variable the way the example above does (a regular def reads better for anything with a name) — their real use is as a throwaway function passed directly into something else, most commonly sorted()'s key argument:
students = [
{"name": "Priya", "age": 21},
{"name": "Amit", "age": 19},
]
# Sort by age, using a lambda to say "compare by this"
students_sorted = sorted(students, key=lambda s: s["age"])
print(students_sorted)key=lambda s: s["age"] tells sorted() what to compare, without needing a separately-named function defined elsewhere just for this one sort.
PHP's array_map() and array_filter() have direct Python equivalents, often paired with a lambda — though a list comprehension (from the earlier lesson) does the same job and is usually considered more readable in modern Python:
numbers = [1, 2, 3, 4, 5]
doubled = list(map(lambda n: n * 2, numbers))
print(doubled) # [2, 4, 6, 8, 10]
# The more idiomatic Python way to write the same thing:
doubled = [n * 2 for n in numbers]