map()

Calls a function for every item and returns an iterator of results.

Returns
An iterator of the function’s results.
On this page

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

#

Spotted a mistake or missing an example? Write to us.