Python Map() function simply returns the map object (an iterator) after apply the created function through list or tuples.
It is hard to understand what map() function does until we apply that in the examples and what it actually does. so, here we will understand this with the below example.
Lets suppose we are creating a function that return cube of the input value. it will return 8 when you put 2. it return 343 when your input value is 7 and so on.
def cube(x): x= x**3 return x cube(7) >> 343
Now suppose we have list with name educatedinfo that contains some values. for example educatedinfo= [2,4,6,8] and i want to apply the above cube function to every item in this list.
First thing come in your mind is applying for loop through each item in the list to return the cube of every items in the list. In map function you don’t have to do it. Simple right?
Map() function in python takes two arguments. first is function and the second is list/tuple etc. now let’s apply the map() function in the above example.
educatedinfo = [2,4,6,8] result= map(cube,educatedinfo) print(list(result)) >> [8, 64, 216, 512]
Let’s understand the concept of map() function with one more example. just remember the more examples you do the more you will understand python and these concepts. i also suggest you to do full python exercise on hacker rank.
In this example we have a list and we have to print whether the value is even or odd.
our_list= [2,3,7,6,5] # we created a list which contains some integer values def oddeven(x): # we created a function named oddeven if x%2 == 0: return 'even' else: return 'odd' result= list(map(oddeven,our_list)) print(result) >> ['even', 'odd', 'odd', 'even', 'odd']
Now, you are ready to apply map function wherever you want it just made your work little easier. Thank you for reading the post.
Also Read: Functions in python