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.
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
my_list = [2, 3, 5, 9] result = map(lambda item: item * item, my_list) result = list(result) # -> [4, 9, 25, 81]
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] print(result)