Python programming language has picked up pace in the last decade. The increasing popularity has brought a lot of demand for python developers in domains like machine learning, data science, etc. One of the main reasons for this growth has been the out of the box features that python comes with. One such function is map function in python, which optimizes the execution of a function with multiple arguments. In this article, we will discuss the map function in detail. The following topics are discussed in this blog.
A map function provides a function for which each item in an iterable can be passed as a parameter. For instance, let’s say we have a function that calculates the length of a string. Using the map function we can specify this function with a list containing a bunch of strings. The output will have the length of each item in the list.
Following is a simple program using the map function to calculate the length of a string in a list.
def func(x): return len(x) a = [ 'Sunday' , 'Monday' , 'Tuesday' , 'Wednesday' , 'Thursday' , 'Friday' , 'Saturday' ] b = map( func , a ) print(list(b))
Output: [ 6 , 6 , 7 , 9 , 8 , 6 , 8 ]
Function – It is a mandatory parameter that stores the function that will be executed using the map function.
Iterable – It stores the iterable which will be passed as an argument in the function. It is a mandatory parameter as well.
res = map(function , iterable)
- Passing two iterables at one time.
def add(a , b): return a + b x = [1,3,5,7,9] y = [2,4,6,8,10] res = map(add , x , y) print(list(res))
Output: [ 3 , 7 , 11 , 15 , 19]
- Program to print cube of the first 10 natural numbers using the map function.
def cube(n): return n*n*n a = list(range(1,11)) res = map(cube , a) print(list(res))
Output: [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
- Program to use lambda function with the map function
a = list(range(1,10)) res = map(lambda x : x*x , a) print(list(res))
Output: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
In this article, we have learned about how we can use map function in python with various examples. By looking at the examples, one can imagine how tidy and readable the code is in the python programming language. Readability and easy syntax are one of the many reasons why python has become so popular in the last decade. With the increasing popularity, the demand has also increased in domains like machine learning, artificial intelligence, data science, etc. To master your skills enroll in edureka’s python certification program and kick-start your learning.
Have any questions? Mention them in the comments. We will get back to you as soon as possible.