Python Glossary Русский

all Python 3Functionsfunction

map()

functional

Applies a function to every item of an iterable. Returns an iterator.

Syntax

map(func, iterable)

map returns a lazy iterator: nothing is computed until you iterate it, and it's empty after the first pass — wrap it in list() if you need the result twice. A comprehension [f(x) for x in xs] often reads more clearly; map wins when the function already exists, as in map(int, strs).

Examples

nums = [1, 2, 3, 4]
result = list(map(lambda x: x**2, nums))
print(result)  # → [1, 4, 9, 16]
strs = ['1','2','3']
ints = list(map(int, strs))
print(ints)  # → [1, 2, 3]
floats = list(map(float, ['1.1','2.2']))
print(floats)  # → [1.1, 2.2]
words = ['hello', 'world']
uppered = list(map(str.upper, words))
print(uppered)  # → ['HELLO', 'WORLD']
# map с несколькими итерируемыми
a = [1, 2, 3]
b = [10, 20, 30]
result2 = list(map(lambda x,y: x+y, a, b))
print(result2)  # → [11, 22, 33]
# map ленивый
m = map(str, range(5))
print(next(m))  # → '0'
print(next(m))  # → '1'
names = ['alice', 'bob']
result3 = list(map(str.capitalize, names))
print(result3)  # → ['Alice', 'Bob']
# map по двум последовательностям сразу
print(list(map(lambda x, y: x + y, [1,2,3], [10,20,30])))  # → [11,22,33]

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy