What are Lambda/anonymous Functions in Python?
Lambda is an anonymous function in Python. Python Lambda Function
There’s two ways to make functions in python: def and lambda.
Def is pretty straightforward, Functions may also be created with the lambda expression, a feature that allows us to in-line function definitions in places where a def statement won’t work syntactically.
Two key distinctions between a lambda expression and a def function:
- lambda is an expression, not a statement. Because of this, a lambda can appear in places a def is not allowed by Python’s syntax—inside a list literal or a function call’s arguments, for example. With def, functions can be referenced by name but must be created elsewhere.
- lambda’s body is a single expression, not a block of statements. Because it is limited to an expression, a lambda is less general than a def—you can only squeeze so much logic into a lambda body without using statements such as if.
Besides those distinctions, def and lambda are pretty similar.
Example
def adder(x, y, z):
return (x + y + z)
The equivalent syntax using a lambda expression would be:
f = lambda x, y, z: x + y + z
Lambda expressions are often used with map, reduce, and filter.
Lambda function with map()
map: It applies a given function to each item of an iterable and returns an iterator.
map(function, iterable)
numbers = [2, 3, 4, 5]
squaredNum = list(map(lambda num: num ** 2 , numbers))
print(squaredNum)
[4, 9, 16, 25]
Lambda function with filter()
filter: It has the same syntax as the map function. It helps in extracting items from an iterable based on the given condition.
filter(function, iterable)
numbers = [2, 3, 4, 5]
evenNum = list(filter( lambda num: num % 2 == 0 , numbers))
print(evenNum)
[2, 4]
Example: Lambda function with reduce()
reduce: It applies a function cumulatively/successively on each item of an iterable and returns a single value.
reduce(function, iterable, [, initializer])
from functools import reduce
numbers = [1, 2, 3, 4, 5]
total = reduce(lambda x, y: x + y, nums)
print(total)
15
When do use lambda function ?
The best use case of a lambda expression is to pass a simple callable to functions such as sort, map, filter.
- Lambda is an anonymous function in Python
- map: It applies a given function to each item of an iterable and returns an iterator.
- filter: It has the same syntax as the map function. It helps in extracting items from an iterable based on the given condition.
- reduce: It applies a function cumulatively/successively on each item of an iterable and returns a single value.