Python: Lambda, Map, Filter and Reduce functions
In Python, normal functions are defined using def keyword followed by function name. For example:
you can see that
myFunc takes x as argument and return x.
But when we talk about: Lambda function, is an anonymous functions are defined using lambda keyword. it uses
lambda keyword without any function name. It can have any number of arguments but only one expression. For example:
Above lambda function is equivalent to:
In python lambda function you can take number of arguments with comma separated but without parenthesis.
Lambda function is assigned to
add_together takes two arguments and return their sum. As per the definition of lambda, list of the arguments with no parenthesis, whereas calling the function is exactly same as normal function with parenthesis surrounding the arguments.
map() is a inbuilt function that allows you to process the each item in an iterable and transform them into new iterable. According to the documentation
map takes function and iterable as an argument and return a new iterable.
map() function syntax is:
function: the function to execute for each item.
iterable: an iterable like: list,tuple etc. You can pass one or more iterable to map.
For example Let’s create a simple function:
In the above example we pass map object
result to list(to create a list). We can also use lambda expression with above example.
The next function is
filter() function. Filter function takes a filtering function and an iterable.
Let’s see a example first. Suppose we have list of integers and want to create a list of even and odd numbers by filtering the integers.
In the above example we use a lambda function as a filtering function. Inside filter function we pass lambda as a filtering function and
integer_list as an argument. The
filter() function return a filter object then to create a list we pass that filter object in
Like Filter function, reduce is also a inbuilt function defined in “functools” module in python. The
reduce() function takes a function and an interable and return a single value.
In the above example value is calculated as follow:
- Initially function is called with first two items in the list and return a value.
- The function is again called with previously value returned in step first and the next value in the list. This process is keep repeating till last value in the list.
Optional arguments: You can also pass an optional argument
initialzer . Let’s add optional argument initializer to above example.
That’s all for today. We learned a bit about python3 lambda expression, how to use it with
reduce() functions with examples.
Feel free to leave a comment or share this post. Follow me for future posts….
If you like this article you may enjoy other articles too.
In this article we will learn comprehension in python and how to use it.
Decorators in Python is an advanced topic. Before we dive into Python Decorator we need to understand the concepts of…