We can create anonymous functions, known as lambda functions. Lambda functions are different from normal Python functions, they origin from Lambda Calculus. It allows you to write very short functions.Related Courses:
- Complete Python Bootcamp: Go from zero to hero in Python
- Automate the Boring Stuff with Python Programming
Lambda function example
This code shows the use of a lambda function:
A return statements is never used in a lambda function, it always returns
something. A lambda functions may contain if statements:
The definition of map is map(function,iterable). It applies a function to every item in the iteratable. We can use map() to on a lambda function with a list:
Anywhere you use lambda functions, you could use normal functions instead. A lambda function is not a statement, it is an expression. Lambda functions do not support a block of statements.
filter(function,iterable) creates a new list from the elmeents for which the function returns True. Example:
The returning list returns contains only the elements for which the lambda expression “lamba x: x % 2 == 0” is true.
The reduce function, reduce(function, iterable) applies two arguments cumulatively to the items of iterable, from left to right. Example:
In this case the expression is always true, thus it simply sums up the elements of the list. Another example: