A lambda function is a small, anonymous function defined in a single expression, without the usual def name(): syntax. Lambdas exist for situations where writing a full function would feel like overkill for something you're only going to use once, typically right where it's passed to another function.
Lambda Syntax
# A regular function
def square(x):
return x ** 2
# The equivalent lambda
square_lambda = lambda x: x ** 2
print(square(5))
print(square_lambda(5))
Output:
25
25
A lambda can take any number of arguments, separated by commas, but its body must be a single expression — there's no return keyword, and you can't fit multiple statements or a loop inside one.
Lambdas with sorted(), map(), and filter()
Lambdas are almost always used inline, as the small piece of logic passed to a function that expects a function argument, most commonly sorted(), map(), and filter().
students = [("Asha", 82), ("Raj", 67), ("Priya", 91)]
# sorted() with a custom sort key
by_score = sorted(students, key=lambda s: s[1], reverse=True)
print(by_score)
# map() applies a function to every item
scores = [68, 74, 90, 55]
curved = list(map(lambda s: s + 5, scores))
print(curved)
# filter() keeps only items where the function returns True
passing = list(filter(lambda s: s >= 70, curved))
print(passing)
Output:
[('Priya', 91), ('Asha', 82), ('Raj', 67)]
[73, 79, 95, 60]
[73, 79, 95]
Using key=lambda s: s[1] tells sorted() exactly what to sort by (the second item of each tuple) without needing a separate named function just for that one comparison.
When to Use a Lambda vs. a Regular Function
Reach for a lambda when the logic is a genuinely short, one-line expression used in a single place — a sort key, a quick transformation, a simple filter condition. If the logic needs a name for clarity, needs more than one line, needs a docstring, or gets reused in several places, write a regular function with def instead; forcing complex logic into a lambda just to save a few lines usually makes the code harder to read, not easier. See our functions tutorial for the full picture on regular function definitions, or our lambda with map, filter, reduce program for a complete worked example.
