Lambda Functions
A lambda function is a small, anonymous function defined using the lambda keyword instead of def. It can take any number of arguments but is limited to a single expression, which is automatically returned.
Lambda Syntax
square = lambda x: x * x
print(square(5)) # 25
This is functionally equivalent to writing a full function definition, just far more compact for simple, one-line logic.
def square(x):
return x * x
Using Lambda with Built-In Functions
Lambda functions are most commonly used as short, throwaway functions passed into other functions like map(), filter(), and sorted().
numbers = [1, 2, 3, 4, 5]
# Double every number
doubled = list(map(lambda x: x * 2, numbers))
# Keep only even numbers
evens = list(filter(lambda x: x % 2 == 0, numbers))
# Sort a list of tuples by the second value
pairs = [(1, "b"), (2, "a")]
pairs.sort(key=lambda p: p[1])
Lambda functions should be reserved for short, simple logic. For anything more complex or reused in multiple places, a regular named function with
def is more readable and maintainable.Coming Up Next
Next, you'll get a tour of some of Python's most useful built-in functions that you'll rely on constantly while working with data.