Lambda functions in Python: A Complete Guide
Lambda functions in Python, also known as anonymous functions, are small, usually one-time functions that are defined using the lambda keyword. Their key feature is that they can contain only one expression and do not have a proper name, which makes them an ideal tool for tasks where a full-fledged definition of a function via def would be redundant. Lambda functions are often used to create short functions on the fly, for example, as arguments to other, higher-level functions.
Main characteristics of lambda functions
- Anonymity: Lambda functions do not have a name, like functions defined via
def. They are function objects that can be assigned to a variable, but this is not their main purpose.
- One expression: A Lambda function can contain only one single expression. It is important to understand that the result of calculating this expression is automatically returned. You don't need to use the
return keyword. This is their main limitation - you cannot place multiple commands, loops, or complex conditional constructions in lambdas.
- Conciseness: The main advantage of lambda functions is the brevity of the code. They allow you not to litter the namespace with one-time functions and make the code more compact in certain situations.
Syntax of lambda functions
The syntax of the lambda function is simple and elegant:
lambda arguments: expression
lambda is the keyword.
arguments are one or more arguments separated by commas (just like in a regular function).
: a colon separating arguments from expressions.
expression - one expression, the result of which will be returned.
Examples of using lambda functions
1. The simplest lambda function
Although lambda functions can be assigned to variables, this is often considered not the best practice. If the function needs a name, it is better to use def. Nevertheless, it is useful for demonstration purposes.
Creating a lambda function that returns the square of a number:
square = lambda x: x ** 2
print(square(5)) # Output: 25
A useful tip: Code verification tools (linters) often mark such an assignment as an antipattern. If you want to give a function a reusable name, a standard definition is preferable.:
def square(x):
return x ** 2
2. Lambda function with multiple arguments
Creating a lambda function that adds two numbers together:
sum = lambda a, b: a + b
print(sum(3, 4)) # Output: 7
3. Using lambda functions with built-in functions
This is where lambda functions really reach their potential. They are ideal for passing map(), filter(), sorted() and others as arguments.
Usage with map()
The map() function applies the specified function to each element of the iterated object and returns an iterator with the results.
numbers = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x ** 2, numbers))
print(squares) # Output: [1, 4, 9, 16, 25]
A useful tip: For simple operations, as in this example, list comprehensions are a more "Pythonic" and often more readable way:
square_alt = [x ** 2 for x in numbers]
print(square_alt) # Output: [1, 4, 9, 16, 25]
Use with filter()
The filter() function returns an iterator consisting only of those elements for which the passed function returned True.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even = list(filter(lambda x: x % 2 == 0, numbers))
print(even numbers) # Output: [2, 4, 6, 8, 10]
A useful tip: Here, too, listing with a condition would be a great alternative.:
even_alt = [x for x in numbers if x % 2 == 0]
print(even_alt) # Output: [2, 4, 6, 8, 10]
Usage with sorted()
The sorted() function returns a new sorted list. Lambda functions are indispensable here for specifying a complex sorting key without having to define a separate function.
students = [("Alice", 25), ("Bob", 22), ("Charlie", 23)]
# Sorting the list of tuples by the second element (age)
sorted students = sorted(students, key=lambda x:x[1])
print(sorted students)
# Output: [('Bob', 22), ('Charlie', 23), ('Alice', 25)]
A useful tip: This is one of the best examples of using lambda. It would be unnecessary to create a separate function def get_age(student): return student[1] just for this one sort.
4. Lambda functions inside other functions (Closures)
Lambda functions can be returned from other functions. This is a powerful technique called closure, where an internal function "remembers" the context in which it was created.
def multiplication(n):
# This function returns another function (lambda)
return lambda x: x * n
# Creating functions based on the multiplication
factory multiplication_2 = multiplication(2) # Here n=2 "remembered"
multiplication_3 = multiplication(3) # Here n=3 "remembered"
print(multiplication to_2(5)) # Output: 10
print(multiplication to_3(5)) # Output: 15
In this example, lambda x:x *n "captures" the value of the variable n from the external function multiplication and stores it for subsequent calls.