Lesson-17: Python Map Function

Python Map Function

The Map () function executes a function specified for each repeatable element. The element is sent to the function as a parameter.


Python Map Function : map(functionrepeated)

Parameter Values:

functionFunction to execute for each element.
repeatedAn array, collection, or iterator object. You can send as many iterables as you want, just make sure that the function has a parameter for each iterable.

Let’s say we have a list like this:liste = [1, 4, 5, 4, 2, 9, 10]

Our goal is to calculate the square of each element in this list. For this purpose, we can follow this path:

for i in liste:
     print(i ** 2)


So, as we wanted, we found the square of all the elements. Another way to do this type of operation is to use an embedded function called map (). Look carefully:

>>> def karesi(n):
...     return n ** 2

Here we have defined a function that calculates the square of the number n. Now we will apply this function on all elements of the “liste” list:

>>> list(map(karesi, liste))

[1, 16, 25, 16, 4, 81, 100]

Example-1 :

def myfunc(a, b):
  return a + b

x = map(myfunc, ('apple', 'banana', 'cherry'), ('orange', 'lemon', 'pineapple'))


['appleorange', 'bananalemon', 'cherrypineapple']

In this example, since the function named myfunc has 2 parameters, there are 2 separate lists in the iterables section of the map. One of these lists is assigned to a and the other to b and goes to the function. As a result, these two values go into the function and are collected. Because there are String values, they are added next to each other and transferred to a separate list.


def toplama(n): 
    return n + n 
no= (1, 2, 3, 4) 
sonuç= map(toplama, no) 

[2, 4, 6, 8]

In this example, no is a tuple, that is, a bunch, and there are 4 numbers in it. the map (toplama, no) function goes to the addition function for each no tuple element and performs operations. We print the result as a list on the screen.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *