Suppose, you have a Python list of items. The items here can be anything numbers, alphabets, words, etc. and you also have a function. You want to apply that function to each and every item on that list. Well, if you have options. You can just iterate the list using various loops like For, While, etc., and apply the function. But why do so when we have a shortcut function for the same in Python?
It’s the Python map() function. The map function can apply any given function to an iterable (List, Tuple, etc.)
The map() Method
- Method Used – map()
- What it Does – Apply the given function to a specified iterable.
- Number of Parameters it takes – 2 (Both are required)
- Return Type – map() Type Object | Simply the Results which are obtained after applying the specified function.
Good To Know: You can combine the result obtained by applying the function on each iterable item using functions like list() and set(). Using the list() function, you can store the results in a Python List, and similarly is the case for the set() function. See the example for a better understanding.
# Defined a Function that returns the number after adding five to it. def addFive(n): return n + 5 #Applying the map() Function data = (1, 2, 3, 4, 5) results = map(addFive, data) print(list(results))
I hope, you got a clear idea of the working of the Python map() function with the above example.
Some more typical examples of the map() Function are given below.
An Example Using Lambda Expression
# Add 5 to all numbers using map and lambda numbers = (1, 2, 3, 4, 5) result = map(lambda x: x + 5, numbers) print(list(result))
An Example of Map Function Using Two Lists and Lambda Expression
# Multipying two lists with Corresponsing Elements using map and lambda list1 = [1, 2, 3] list2 = [4, 5, 6] results = map(lambda x, y: x * y, list1, list2) print(list(results))
Thus, there could be a lot of uses for the Python map() function.