PythonBuilt-in functions
map()
Calls a function for every item and returns an iterator of results.
- Returns
- An iterator of the function’s results.
Example
#Python
values = ["12", "7", "30"]
numbers = list(map(int, values))
print(numbers)
print(sum(numbers))
print(list(map(str.upper, ["html", "css"])))Resultsaved result, you can check it
[12, 7, 30]
49
['HTML', 'CSS']
Definition and usage
#The map(function, collection) function applies the given function to every item and returns an iterator of results. To see all the results at once, pass it to list().
With several collections, the function receives one item from each of them: map(pow, [2, 3], [3, 2]) gives 8 and 9.
In many cases a list comprehension is more readable: [int(x) for x in values] instead of list(map(int, values)). map works well when you already have a function ready to pass.
Syntax
#Syntax
map(function, iterable, *iterables)Parameters
#function
callable
The function applied to each item.iterable
a collection
The items to transform.
Good practices
#- The result of
map()can only be walked through once. If you need it several times, convert it to a list. - For transformations with a condition, a list comprehension is more readable.
Related entries
#- map() vs list comprehensionmap() calls a function for every element and returns a lazy iterator, while a list comprehension builds a new list right away and can filter with an if condition.
- filter()Returns an iterator of items for which a function returns a truthy value.
- List comprehensionsA concise way to build lists, sets, and dictionaries from other collections.
- lambdaA short anonymous function written as a single expression.
- sum()Adds together all the numbers in a collection.
Spotted a mistake or missing an example? Write to us.