Python map
last modified November 18, 2026 Python 3.15
In this article we show how to use the Python built-in map
function.
The map function
The map built-in function applies a function to every item of
one or more iterables and returns an iterator over the results.
map(function, iterable, *iterables, strict=False)
When more than one iterable is passed, the function must accept as many
arguments as there are iterables; it is called with one item from each.
By default, map stops when the shortest iterable is exhausted.
The strict parameter was added in Python 3.14.
A simple example
The following example uses map on a list of integers.
def square(x):
return x * x
nums = [1, 2, 3, 4, 5]
squared = map(square, nums)
print(squared)
for num in squared:
print(num, end=' ')
print()
We apply the square function to each element of the list.
squared = map(square, nums)
We pass the function object itself, without calling it. The
map function returns a map object, which is an
iterator, not a list.
for num in squared:
print(num, end=' ')
We loop over the iterator and print the squared values.
$ python square_map.py <map object at 0x7bb604866f80> 1 4 9 16 25
Lazy evaluation
The map function does not compute anything when it is called.
Each result is computed only when the iterator is asked for the next value.
Like all iterators, a map object can be consumed only once.
def square(x):
print(f'computing {x}')
return x * x
squared = map(square, [1, 2, 3])
print('map created')
print(next(squared))
print(list(squared))
print(list(squared))
The square function prints a message every time it runs.
print(next(squared)) print(list(squared)) print(list(squared))
The next function computes the first value. The
list function consumes the remaining ones. The second
list call gets an empty list because the iterator is already
exhausted.
$ python lazy_map.py map created computing 1 1 computing 2 computing 3 [4, 9] []
A map equivalent
The behaviour of map can be written as a small generator
function.
def mymap(func, *iterables):
for args in zip(*iterables):
yield func(*args)
print(list(mymap(abs, [-1, 2, -3])))
print(list(mymap(pow, [2, 3, 4], [3, 2])))
print(list(map(pow, [2, 3, 4], [3, 2])))
The mymap generator zips the iterables together and calls the
function with the unpacked items. Like map, it stops at the
shortest iterable, so 4 has no exponent and is ignored.
$ python mymap.py [1, 2, 3] [8, 9] [8, 9]
Map with lambda
For short one-off operations, the function is often created inline with a
lambda expression.
nums = [1, 2, 3, 4, 5] print(list(map(lambda x: x * x, nums))) prices = [12.5, 7.9, 23.0] print(list(map(lambda p: round(p * 1.2, 2), prices)))
We square a list of numbers and add 20 % to a list of prices.
$ python map_lambda.py [1, 4, 9, 16, 25] [15.0, 9.48, 27.6]
Built-in functions and methods
Any callable can be passed to map: built-in functions, types
such as int and float, and unbound methods such as
str.strip. This avoids a lambda.
words = ['sky', ' cup ', 'Forest', 'war '] print(list(map(str.strip, words))) print(list(map(str.upper, words))) print(list(map(len, words))) line = '4 8 15 16 23 42' nums = list(map(int, line.split())) print(nums, sum(nums)) print(list(map(float, ['1.5', '2', '-3e2'])))
We strip, uppercase, and measure a list of words and convert strings to numbers.
print(list(map(str.strip, words)))
str.strip called with a string as its argument is the same as
calling the method on that string.
nums = list(map(int, line.split()))
Converting the fields of a line of text to integers is one of the most
common uses of map.
$ python builtin_funcs.py ['sky', 'cup', 'Forest', 'war'] ['SKY', ' CUP ', 'FOREST', 'WAR '] [3, 5, 6, 4] [4, 8, 15, 16, 23, 42] 108 [1.5, 2.0, -300.0]
Multiple iterables
With several iterables, map calls the function with one item
from each iterable.
import operator nums1 = [1, 2, 3, 4, 5] nums2 = [6, 7, 8, 9, 10] print(list(map(lambda x, y: x * y, nums1, nums2))) print(list(map(operator.mul, nums1, nums2))) print(list(map(max, [3, 9, 1], [4, 2, 8], [5, 5, 5]))) print(list(map(pow, [2, 3, 4], [5, 2])))
We multiply the items of two lists pairwise, pick the maximum from three lists, and raise numbers to powers.
print(list(map(operator.mul, nums1, nums2)))
The operator module provides functions for Python operators,
so operator.mul replaces lambda x, y: x * y.
print(list(map(pow, [2, 3, 4], [5, 2])))
The second list is shorter, so only two results are produced.
$ python multiple_iterables.py [6, 14, 24, 36, 50] [6, 14, 24, 36, 50] [5, 9, 8] [32, 9]
The strict parameter
Silently dropping the extra items of a longer iterable can hide bugs. Since
Python 3.14, strict=True makes map raise
ValueError when the iterables have different lengths, like
zip does. Older versions reject the keyword with a
TypeError.
names = ['Peter', 'Lucia', 'Tom']
ages = [34, 28]
try:
for line in map('{} is {}'.format, names, ages, strict=True):
print(line)
except ValueError as e:
print('error:', e)
We pair three names with two ages. The bound method
'{} is {}'.format takes two arguments, one from each list.
The length mismatch is detected only when the shorter iterable runs out, so the first two lines are printed before the error.
$ python map_strict.py Peter is 34 Lucia is 28 error: map() argument 2 is shorter than argument 1
The starmap function
When the arguments are already grouped in tuples, the
itertools.starmap function unpacks each tuple into the
function's arguments.
from itertools import starmap
points = [(2, 3), (4, 1), (5, 5)]
print(list(starmap(pow, points)))
print(list(map(lambda p: pow(*p), points)))
items = [('pen', 3, 1.2), ('book', 1, 14.5), ('cup', 4, 3.0)]
for line in starmap(lambda name, qty, price: f'{name:5} {qty * price:6.2f}', items):
print(line)
The starmap(pow, points) call computes pow(2, 3),
pow(4, 1), and pow(5, 5). With map
we would have to unpack the tuple ourselves.
for line in starmap(lambda name, qty, price: f'{name:5} {qty * price:6.2f}', items):
Each tuple of an item, quantity, and price is unpacked into three parameters and formatted into an invoice line.
$ python starmap_ex.py [8, 4, 3125] [8, 4, 3125] pen 3.60 book 14.50 cup 12.00
Applying several functions
We can also map over a collection of functions and call each one with the same value.
def double(x):
return x + x
def square(x):
return x * x
funcs = (double, square, str)
for n in [1, 2, 3]:
vals = list(map(lambda f: f(n), funcs))
print(vals)
For each number, we build a list with the results of three functions.
vals = list(map(lambda f: f(n), funcs))
Here the iterable holds the functions and the lambda calls each of them with the current number.
$ python multiple_funcs.py [2, 1, '1'] [4, 4, '2'] [6, 9, '3']
Mapping dictionaries
map works with any iterable, including lists of dictionaries
and dictionary views.
from operator import itemgetter
users = [
{'name': 'John Doe', 'salary': 1200},
{'name': 'Lucy Smith', 'salary': 1500},
{'name': 'Roger Roe', 'salary': 980},
]
names = list(map(lambda u: u['name'], users))
print(names)
print(list(map(itemgetter('salary'), users)))
stock = {'apples': 12, 'pears': 0, 'plums': 7}
print(dict(map(lambda kv: (kv[0].upper(), kv[1] * 2), stock.items())))
We extract fields from a list of user records and transform a dictionary.
print(list(map(itemgetter('salary'), users)))
itemgetter('salary') creates a function that returns the
salary item of its argument.
print(dict(map(lambda kv: (kv[0].upper(), kv[1] * 2), stock.items())))
Mapping the items view to new key-value pairs and passing them
to dict creates a transformed dictionary.
$ python map_dict.py
['John Doe', 'Lucy Smith', 'Roger Roe']
[1200, 1500, 980]
{'APPLES': 24, 'PEARS': 0, 'PLUMS': 14}
Map and filter
map is often combined with filter or with
functions that consume an iterable, such as sum and
max.
nums = [3, -1, 8, 0, -5, 6] squares = map(lambda x: x * x, filter(lambda x: x > 0, nums)) print(list(squares)) print([x * x for x in nums if x > 0]) print(sum(map(abs, nums))) print(max(map(len, ['sky', 'forest', 'cup'])))
We square the positive numbers, first with map and
filter, then with a list comprehension.
print(sum(map(abs, nums)))
Because map is lazy, no intermediate list is created; the
values are passed directly to sum.
$ python map_filter.py [9, 64, 36] [9, 64, 36] 23 6
Map and comprehensions
List comprehensions and generator expressions do the same job as
map and are often more readable, especially when a lambda would
be needed.
nums = [1, 2, 3, 4, 5] print(list(map(lambda x: x * x, nums))) print([x * x for x in nums]) print(list(map(str, nums))) print([str(x) for x in nums]) squares = (x * x for x in nums) print(squares) print(sum(squares))
Each pair of lines produces the same list.
squares = (x * x for x in nums)
A generator expression is lazy like map. As a rule of thumb,
map reads well with an existing named function such as
str or int; a comprehension reads better with an
expression.
$ python comprehension.py [1, 4, 9, 16, 25] [1, 4, 9, 16, 25] ['1', '2', '3', '4', '5'] ['1', '2', '3', '4', '5'] <generator object <genexpr> at 0x7c9627034580> 55
Mapping file lines
A file object iterates over its lines, so we can map a function over a file without reading it into a list. We use the following file.
10 20 30 40
The file contains one number per line.
from pathlib import Path
files = ['data.txt', 'notes.md', 'report.txt']
print(list(map(Path, files)))
print(list(map(lambda p: Path(p).suffix, files)))
with open('nums.txt', encoding='utf-8') as f:
total = sum(map(int, f))
print(total)
We create Path objects from file names, extract their suffixes,
and sum the numbers in the file.
total = sum(map(int, f))
The int function ignores surrounding whitespace, so the
trailing newlines do not need to be stripped.
$ python map_files.py
[PosixPath('data.txt'), PosixPath('notes.md'), PosixPath('report.txt')]
['.txt', '.md', '.txt']
100
Concurrent map
The map method of the executors in
concurrent.futures works like the built-in function but runs
the calls concurrently in threads or processes. The results are returned in
the order of the input.
import time
from concurrent.futures import ThreadPoolExecutor
def fetch(n):
time.sleep(1)
return f'result {n}'
start = time.perf_counter()
with ThreadPoolExecutor(max_workers=4) as executor:
for res in executor.map(fetch, range(4)):
print(res)
print(f'elapsed: {time.perf_counter() - start:.1f} s')
The fetch function simulates a slow I/O operation that takes a
second.
with ThreadPoolExecutor(max_workers=4) as executor:
for res in executor.map(fetch, range(4)):
print(res)
Four worker threads run the four calls at the same time, so the whole loop takes about one second instead of four.
$ python executor_map.py result 0 result 1 result 2 result 3 elapsed: 1.0 s
Source
map – Python built-in functions
In this article we have worked with the Python map function.
See also Python filter list,
Python lambda functions,
Python list comprehensions, and
Python for loop.
Author
List all Python tutorials.