Python Lambda Functions Tutorial Guide
Lambda Functions in Python
Lambda functions are a convenient way to declare small anonymous functions in Python. Unlike regular functions, which are declared using the def keyword, lambda functions are declared using the keyword lambda. They are generally used in situations where you want to pass a function as an argument for another function (such as a callback).
Syntax
The syntax for a lambda function is relatively simple: it consists of the keyword lambda
, followed by one or more arguments, separated by commas, followed by a colon and a single expression. The expression is the body of the lambda function, and it is evaluated and returned when the function is called.
lambda argument_list: expression
Examples
Here are some examples of lambda functions:
f = lambda x: x + 1 # Add 1 to x
g = lambda x, y: x * y # Multiply x and y
h = lambda x, y, z: x + y + z # Add x, y and z together
These functions can be used just like any other function:
x = 10
y = 5
z = 20
print(f(x)) # Prints 11
print(g(x, y)) # Prints 50
print(h(x, y, z)) # Prints 35
Using Lambdas with Other Functions
One of the main uses of lambda functions is in combination with other functions. For example, you can use them with the built-in map()
function to apply a given operation to each element in a list:
numbers = [1, 2, 3, 4, 5]
# Use map() and a lambda function to double each element in the list
doubled = map(lambda x: x * 2, numbers)
print(list(doubled)) # Prints [2, 4, 6, 8, 10]
Lambda functions can also be used with the built-in filter()
function, to filter out elements from a list that do not satisfy a given condition:
numbers = [1, 2, 3, 4, 5]
# Use filter() and a lambda function to keep only the even numbers
evens = filter(lambda x: x % 2 == 0, numbers)
print(list(evens)) # Prints [2, 4]
Conclusion
Lambda functions are a convenient way to declare small, anonymous functions in Python. They can be used in combination with other functions, such as filter(), map(), reduce() and sorted(). They are often used in situations where a function needs to be passed as an argument, such as in callbacks or event handlers.