A lambda is a small, unnamed function limited to a single expression.
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.
map() and filter() are Python's functional-style tools for transforming and filtering, 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]filter() is the other half — it keeps only the items where the lambda returns something truthy:
numbers = [1, 2, 3, 4, 5, 6]
even = list(filter(lambda n: n % 2 == 0, numbers))
print(even) # [2, 4, 6]
# The more idiomatic Python way to write the same thing:
even = [n for n in numbers if n % 2 == 0]Both map() and filter() return a lazy iterator, not a list directly — which is why list(...) wraps them above to actually see the results.