Background
The map() function comes from functional programming (even from Lisp), its purpose is to apply a function to each element of a sequence, returning a new iterable object with the results. In Python, it appeared long before the introduction of generator expressions and list comprehensions, but it is still widely used, especially in large data processing pipelines.
Problem
When it is necessary to modify each element of a collection according to some rule, solutions such as for loops quickly become cumbersome and less readable. List comprehensions and map() allow expressing intentions compactly. At the same time, it is important to understand the differences between these approaches to choose the right tool.
Solution
map(func, iterable) creates a lazy iterator where the elements of the original sequence are transformed by the func function.def square(x): return x * x squares = map(square, [1, 2, 3]) print(list(squares)) # [1, 4, 9]
The list comprehension [square(x) for x in [1, 2, 3]] does the same, but immediately returns a list, while the generator expression (square(x) for x in [1, 2, 3]) is a lazy generator.
Key Features:
Does map() return a list in Python 3?
No, starting from Python 3, map() returns not a list, but a lazy iterator. To obtain a list, you need to manually wrap the result in list().
res = map(str.upper, ['a', 'b']) print(res) # <map object ...> print(list(res)) # ['A', 'B']
Can you use map() to add a filtering condition inside the function?
No, map() does not filter elements, it only transforms. For filtering, use filter() or a list comprehension:
result = map(str.upper, ['a', 'b', None]) # If None comes through, map will call str.upper(None) error. # filter will help remove None before map.
Can you use map() to iterate over two sequences simultaneously?
Yes, map() can take an arbitrary number of sequences, and the transformation function must take the same number of arguments:
x = [1, 2, 3] y = [10, 20, 30] result = map(lambda a, b: a + b, x, y) print(list(result)) # [11, 22, 33]
A developer expects to get a list immediately:
mapped = map(abs, [-1, -2, -3]) print(mapped[1]) # TypeError: 'map' object is not subscriptable
Pros:
Cons:
Using a generator expression for filtering and map() for transformation:
nums = range(-5, 6) positives = (x for x in nums if x > 0) sq = map(lambda n: n * n, positives) print(list(sq)) # [1, 4, 9, 16, 25, 36]
Pros:
Cons: