Apply a Function to Items of a List in Python: map()
In Python, you can use map()
to apply built-in functions, lambda expressions (lambda
), functions defined with def
, etc., to all items of iterables, such as lists and tuples.
Note that map()
can be substituted by list comprehensions or generator expressions. As described later, it is preferable to use them in many cases.
Basic usage of map()
The first argument of map()
is a callable object, such as a function to be applied, and the second argument is an iterable object, such as a list.
map()
returns an iterator in Python3
Apply the built-in function abs()
which returns the absolute value.
In Python 3, map()
returns an iterator of type map
. Note that using print()
directly on this object will not output its items.
l = [-2, -1, 0]
print(map(abs, l))
# <map object at 0x10651a400>
print(type(map(abs, l)))
# <class 'map'>
The value of the iterator can be retrieved with a for
statement.
for i in map(abs, l):
print(i)
# 2
# 1
# 0
The same result is obtained if the process is executed in a for
block without using map()
.
for i in l:
print(abs(i))
# 2
# 1
# 0
Note that map()
in Python 2 returns a list, which might cause issues when running Python 2 code in Python 3.
Convert to a list
If you want to convert the result of map()
to a list, use list()
.
l = [-2, -1, 0]
print(list(map(abs, l)))
# [2, 1, 0]
For example, apply len()
to a list of strings to convert it to a list of the number of characters.
l_s = ['apple', 'orange', 'strawberry']
print(list(map(len, l_s)))
# [5, 6, 10]
In the second argument of map()
, not only a list but also an iterable such as a tuple or range
can be specified.
print(list(map(abs, range(-2, 1))))
# [2, 1, 0]
Apply lambda expressions (lambda
)
If you want to apply any process instead of a built-in function, use lambda expression (lambda
).
l = [-2, -1, 0]
print(list(map(lambda x: x**2, l)))
# [4, 1, 0]
Apply functions defined with def
It is also possible to define a function with def
and specify it as the first argument of map()
.
l = [-2, -1, 0]
def square(x):
return x**2
print(list(map(square, l)))
# [4, 1, 0]
Specify multiple iterables as arguments
You can specify multiple iterables in map()
like map(function, iterable1, iterable2, ...)
.
If multiple iterables are specified, the first argument must be a function that receives that number of arguments. An error is raised if the number of iterables does not match the number of arguments that the function receives.
l_1 = [1, 2, 3]
l_2 = [10, 20, 30]
print(list(map(lambda x, y: x * y, l_1, l_2)))
# [10, 40, 90]
# print(list(map(abs, l_1, l_2)))
# TypeError: abs() takes exactly one argument (2 given)
If the iterables have different sizes (number of items), the extra items are ignored.
l_3 = [100, 200, 300, 400]
print(list(map(lambda x, y, z: x * y * z, l_1, l_2, l_3)))
# [1000, 8000, 27000]
Use list comprehensions and generator expressions instead
The same process as map()
can be achieved with list comprehensions and generator expressions.
l = [-2, -1, 0]
print([abs(x) for x in l])
# [2, 1, 0]
print([x**2 for x in l])
# [4, 1, 0]
l_1 = [1, 2, 3]
l_2 = [10, 20, 30]
print([x * y for x, y in zip(l_1, l_2)])
# [10, 40, 90]
If you want to get a list like list(map())
, use the list comprehensions, and if you want to get an iterator like map()
, use a generator expression.
As shown in the following Stack Overflow question, in most cases, using list comprehensions and generator expressions is preferable to map()
because the code is more concise and clear.
For processing speed, the following answers were provided.
- python - List comprehension vs map - 40948713 - Stack Overflow
- List comprehensions and
list(map())
- When applying built-in functions,
list(map())
is faster. - When applying lambda expressions, list comprehension is faster.
- When applying built-in functions,
- Generator expressions and
map()
map()
is faster.
- List comprehensions and
Keep in mind that processing speed can vary due to various factors. If speed is crucial for your use case, it is recommended to perform measurements under conditions that closely match your actual usage.
Use NumPy instead
In the case of a list of numbers, the process of map()
can also be realized with NumPy. The code is even clearer than map()
and list comprehensions.
import numpy as np
a = np.array([-2, -1, 0])
print(np.abs(a))
# [2 1 0]
print(a**2)
# [4 1 0]
a_1 = np.array([1, 2, 3])
a_2 = np.array([10, 20, 30])
print(a_1 * a_2)
# [10 40 90]
NumPy is faster for large lists and complex processing. NumPy provides various functions, so you should try them if you are processing an array of numbers.