The map() function in Python

Quick-start on Python’s built-in library function map().


map() returns an iterator that applies a function to each item in an iterable:

map(function, iterable)

The iterator is evaluated lazily - it won’t traverse the list until another function requires it.

All sequences in Python are iterable. Custom types are iterable if they implement the __iter__() method.


Convert all elements in a list to a string using the builtin str():

numbers = [1, 2, 3]
iterator = map(str, numbers)
strings = list(iterator)

Double all elements in a list using a custom function:

numbers = [1, 2, 3]

def double_it(value):
    return value * 2

iterator = map(double_it, numbers)
doubled = list(iterator)

Further Reading