Search code snippets, questions, articles...

map() function in python

To apply a function on all elements of an iterable element like a list we can use the python map() function.
my_list = [2, 3, 5, 9]

def multiply(item):
  return item * item

result = map(multiply, my_list)

result = list(result)

# -> [4, 9, 25, 81]

Python map() function is used to apply a given function to the elements of a list. We can also use the map to convert a sequence (list) into another set of values. The map() function takes two arguments, first the function that needs to be applied on a set of values, and second the sequence you want to run through. Let's take a look at some examples.

Steps by step description of map() function applied in the above code snippet

1. We have defined a list variable my_list that contains multiple integers.

2. Defined a function named multiply that takes the list item as a parameter and returns the value by multiplying the item itself.

3. Using map() function and passing multiply function and my_list to it. Storing the result in result named variable.

map(function, iterable) parameters

There are two parameters that are passed to the map() function in python.

function: It is the method that is applied to each element of an iterable list or item.

Iterable: You can use a list or other iterable items as this parameter.

Basic syntax of map() function

map(myfunc, iter_item)
my_list = [2, 3, 5, 9]

result = map(lambda item: item * item, my_list)

result = list(result)

# -> [4, 9, 25, 81]
You can also use lambda expressions inside map() function to apply some expression on all the items of the list. In the above code, we have generated new list from a list of items that multiply itself.
list1 = [4, 6, 9, 10]
list2 = [5, 2, 4, 5]

result = map(lambda x, y: x * y, list1, list2)

result = list(result)

# -> [20, 12, 36, 50]

We can pass more than one list in the python map() function. Using the above code we are multiplying two list items with their respective index.
Was this helpful?
Programming Feeds
Learn something new everyday on Devsheet