Syntax
lambda arguments: expressionExamples
Basic Lambda
Comparing a lambda to an equivalent regular function.
square = lambda x: x ** 2
print(square(5)) # 25
# Equivalent regular function
def square_normal(x):
return x ** 2Lambda with sorted()
Using a lambda as the 'key' function to control sort order.
students = [
{"name": "Fola", "grade": 85},
{"name": "Zain", "grade": 92},
{"name": "Jamal", "grade": 78}
]
by_grade = sorted(students, key=lambda s: s["grade"], reverse=True)
for s in by_grade:
print(s["name"], s["grade"])Lambda with map() and filter()
Using lambdas as quick, inline transformation and filter functions.
numbers = [1, 2, 3, 4, 5]
doubled = list(map(lambda n: n * 2, numbers))
print(doubled) # [2, 4, 6, 8, 10]
evens = list(filter(lambda n: n % 2 == 0, numbers))
print(evens) # [2, 4]Lambda with Multiple Arguments
Lambdas can accept multiple parameters, just like regular functions.
add = lambda a, b: a + b
print(add(3, 4)) # 7
# Lambda with a default argument
greet = lambda name, greeting="Hello": f"{greeting}, {name}!"
print(greet("Fola"))
print(greet("Fola", "Hey"))Best practices
- Use lambdas for short, throwaway functions passed as arguments (sort keys, map/filter callbacks) - not for complex logic
- Prefer a regular def function once a lambda's expression starts feeling hard to read on one line
- Avoid assigning a lambda to a variable name just to give it a name - use def instead, since it's more readable and gives better error tracebacks
- Remember a lambda can only contain a single expression, not statements like assignments, loops, or multiple lines
At a glance
- Purpose
- Scripting and general-purpose applications
- File extension
- .py
- Runs in
- Python interpreter
- Usually used with
- Python standard library and packages
Specifications & further reading
Related Python documentation
def
The def keyword in Python is used to define functions - reusable blocks of code that perform specific tasks. Functions are fundamental to organizing code, avoiding repetition, and making programs more maintainable. A function can accept inputs (parameters), perform operations, and return outputs. Functions are one of the core building blocks of clean, modular Python code.return
The return statement exits a function immediately and optionally sends a value back to the caller. A function can return any type - including multiple values as a tuple - or nothing at all, in which case it implicitly returns None. Once return executes, no further code in the function runs, making it useful for early exits as well as producing a final result.*args and **kwargs
*args and **kwargs let a function accept a variable number of arguments. *args collects any extra positional arguments into a tuple, while **kwargs collects extra keyword arguments into a dictionary. The names 'args' and 'kwargs' are just convention - what matters is the * and ** prefixes. This pattern is common in wrapper functions, decorators, and APIs that need to stay flexible about their inputs.Decorators
A decorator is a function that wraps another function to extend or modify its behavior, without changing its actual source code. Decorators use the @decorator_name syntax placed directly above a function definition, which is shorthand for passing the function into the decorator and reassigning the result. They're widely used for logging, timing, access control, caching, and validation.
The def keyword in Python is used to define functions - reusable blocks of code that perform specific tasks. Functions are fundamental to organizing code, avoiding repetition, and making programs more maintainable. A function can accept inputs (parameters), perform operations, and return outputs. Functions are one of the core building blocks of clean, modular Python code.return
The return statement exits a function immediately and optionally sends a value back to the caller. A function can return any type - including multiple values as a tuple - or nothing at all, in which case it implicitly returns None. Once return executes, no further code in the function runs, making it useful for early exits as well as producing a final result.*args and **kwargs
*args and **kwargs let a function accept a variable number of arguments. *args collects any extra positional arguments into a tuple, while **kwargs collects extra keyword arguments into a dictionary. The names 'args' and 'kwargs' are just convention - what matters is the * and ** prefixes. This pattern is common in wrapper functions, decorators, and APIs that need to stay flexible about their inputs.Decorators
A decorator is a function that wraps another function to extend or modify its behavior, without changing its actual source code. Decorators use the @decorator_name syntax placed directly above a function definition, which is shorthand for passing the function into the decorator and reassigning the result. They're widely used for logging, timing, access control, caching, and validation.