Python Reference ยท Built-in Functions
Python map() function
Reference for Python map(): apply a function to every item of one or more iterables, lazy iterator results, multiple iterables, strict mode and comprehensions.
The map() function applies a function to every item of an iterable and gives you the results. It does not build a list: it returns a lazy map iterator that computes each result only when you ask for the next one.
map() suits cases where you already have a named function, such as str.upper or int. When the transformation needs a lambda, a list comprehension is usually easier to read.
print(list(map(len, ["a", "bb", "ccc"]))) # [1, 2, 3]
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
map(function, iterable) map(function, iterable, *iterables, strict=False)
| Name | Description |
|---|---|
function |
A callable that takes as many arguments as there are iterables. |
iterable |
The first iterable whose items are passed to function. |
*iterables |
Optional more iterables. Items are taken in parallel, one from each. |
strict |
Optional keyword-only, added in 3.14. If true, a ValueError is raised when the iterables have different lengths. |
Return value: a map iterator that yields function(item) for each item.
Raises: TypeError if an argument is not iterable or the function takes the wrong number of arguments (raised when the item is processed, not when map() is called). With strict=True, ValueError for unequal lengths.
Usage notes
- Lazy. Nothing runs until you iterate.
map(print, items)prints nothing until consumed, and an iterator can be consumed only once. - Stops at the shortest iterable unless
strict=True(Python 3.14 and later; older versions have no such parameter). - Python 2 difference. There
map()returned a list. In Python 3 wrap it inlist()when you need one. - Prefer comprehensions when you would otherwise write a
lambda:[n * n for n in nums]is clearer thanmap(lambda n: n * n, nums), and also allowsiffilters. - Good fit when passing an existing function:
map(int, parts),map(str.strip, lines). - Side effects are better written as a
forloop; usingmap()for them hides intent. - Memory. Because it is lazy,
map()can handle huge or infinite inputs. - Multiple iterables replace
zipplus unpacking, butitertools.starmap()is the tool when items are already tuples.