Python map() Function
The map() function applies a function to every item of an iterable (like a list or tuple) and returns a map object, which is an iterator. You can turn it into a list, tuple or set.
Syntax
map(function, iterable, ...)
| Parameter | Description |
|---|---|
| function | The function to run on each item |
| iterable | A list, tuple, string or any iterable. You can pass more than one iterable |
Examples
Example 1: length of each word
def get_length(word):
return len(word)
result = map(get_length, ("volvo", "honda", "tata"))
print(list(result))
Output of the above program is
[5, 5, 4]
If you print the map object itself, you see only something like <map object at 0x...>, so convert it with list() to see the values.
Example 2: two iterables
When you pass two iterables, the function must take two arguments. It takes one item from each, in order.
def join_words(a, b):
return a + b
result = map(join_words, ("lemon", "banana", "avocado"), ("orange", "mango", "pineapple"))
print(list(result))
Output of the above program is
['lemonorange', 'bananamango', 'avocadopineapple']
Example 3: with a lambda
numbers = [1, 2, 3, 4]
print(list(map(lambda x: x * x, numbers)))
Output of the above program is
[1, 4, 9, 16]
Example 4: change the type of every item
print(list(map(int, ["1", "2", "3"])))
Output of the above program is
[1, 2, 3]
Note:
A map object can be used only once. After you convert it to a list, the map object is empty. Many developers also use a list comprehension, like [x * x for x in numbers], which does the same work.
Summary
map()runs a function on every item and returns an iterator.- Use
list()to see the result. - It works with many iterables if the function takes the same number of arguments.
- Related: filter(), reduce() and lambda.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |