We want to add 1 in every element of our integer list. How can we do that? There is a smart way to do this in Python, and we can do this by using the map function. It’s a built-in Python function. Using map function you can do anything in your every element.
Basically, the map() takes two arguments. The first argument is a function and second is iterable. Each element from iterable gone through the first argument which is a function. Inside this function, we will find every element as a parameter. After completing our task we will return it. In the end, this map function returns a map object. Let’s look at an example.
lst = [10, 20, 30, 40, 50] # iterable # Receive each element from the list as a parameter def add_one(el): return el + 1 res = map(add_one, lst) convert_to_list = list(res) print(convert_to_list) # Result = [11, 21, 31, 41, 51]
We can convert this map objects into a list, set, tuple. Let’s look at another example. It takes a string list and converts each element to an uppercase letter.
lst = ['a', 'b', 'c', 'd', 'f'] # iterable def to_upper(el): return el.upper() res = map(to_upper, lst) convert_to_list = list(res) print(convert_to_list) # Result = ['A', 'B', 'C', 'D', 'E']
So, That’s the intro of Python map() function. I hope, a bit of the help you got from this article. You can learn more from the official docs.