How to use Python map()
By Flavio Copes
Learn how to use the Python map() function to run a function on every item of an iterable and build a new list, using a named or inline lambda function.
map() runs a function on each item of an iterable, like a list, and returns the results as a new collection with the same number of items. It’s one of 3 useful global functions Python provides to work with collections, along with filter() and reduce().
Tip: sometimes list comprehensions make more sense and are generally considered more pythonic
Here’s map() used to double each item in a list:
numbers = [1, 2, 3]
def double(a):
return a * 2
result = map(double, numbers)
When the function is a one-liner, it’s common to use a lambda function:
numbers = [1, 2, 3]
double = lambda a : a * 2
result = map(double, numbers)
and even inline it:
numbers = [1, 2, 3]
result = map(lambda a : a * 2, numbers)
The original list is left untouched.
The result is not a list
map() returns a map object, an iterator. To print its content, you need to cast it to a list:
print(list(result)) # [2, 4, 6]
This laziness is intentional. Values are computed only when you iterate over them, so with a huge collection nothing happens until you actually consume the results.
But there’s a catch: an iterator can be consumed only once.
result = map(lambda a : a * 2, [1, 2, 3])
print(list(result)) # [2, 4, 6]
print(list(result)) # []
The second call prints an empty list, because the iterator is exhausted. If you need the values more than once, store list(result) in a variable and use that.
Using map() with multiple iterables
You can pass more than one iterable to map(). The function must accept one argument per iterable:
prices = [1.5, 2.25, 3.0]
quantities = [2, 3, 1]
totals = map(lambda price, qty: price * qty, prices, quantities)
print(list(totals)) # [3.0, 6.75, 3.0]
If the iterables have different lengths, map() stops at the shortest one. The extra items in the longer iterable are ignored.
The list comprehension alternative
For simple cases like doubling numbers, a list comprehension does the same job:
numbers = [1, 2, 3]
result = [a * 2 for a in numbers]
This gives you a real list right away, no cast needed. map() shines when you already have the function defined, or when you want the lazy evaluation.
Related posts about python: