Before reading this article, please make sure you understand how the lambda function works.
Like zip() and filter(), map can create and return a generator. generator is an implementation of iterator with lazy evaluation features, which can reduce memory usage very effectively.
map() performs the corresponding operation you give to all the elements in the iterable object. For example, in the following example, we replace each word in a string list with its corresponding character length.
li = ['a', 'apple', 'alphabet']
li = [*map(lambda x: len(x), li)]
# li = [1, 5, 8]
The above map() approach can actually be achieved using the list comprehensions below.
li = ['a', 'apple', 'alphabet']
li = [len(s) for s in li]
# li = [1, 5, 8]
Map can operate on multiple lists at once.
Combine the elements of each position in the two lists.
num = [0, 1, 2]
li = ['a', 'apple', 'alphabet']
combined = [*map(lambda x, y: str(x) + y, num, li)]
# combined = ['0a', '1apple', '2alphabet']
Find the largest element in each position of the three lists.
num1 = [100, 1, 20]
num2 = [19, 4, 94]
num3 = [40, 6, 30]
m = [*map(lambda x, y, z: max(x, y, z), num1, num2, num3)]
# m = [100, 6, 94]
In fact, these implementation can also be achieved with the zip() method and list comprehension.
num = [0, 1, 2]
li = ['a', 'apple', 'alphabet']
combined = [str(x) + y for (x, y) in zip(num, li)]
# combined = ['0a', '1apple', '2alphabet']
num1 = [100, 1, 20]
num2 = [19, 4, 94]
num3 = [40, 6, 30]
m = [max(tup) for tup in zip(num1, num2, num3)]
# m = [100, 6, 94]