Note
Python - map() - Apply a function to all elements in an iterable
Overview of the Python map() function. Apply function to each item of an iterable
map(function, iterable) applies a given function to each item of an iterable (or multiple iterables) and returns a lazy iterator with the results.
That means, that map() function will run provided function on each object of given iterable or multiple iterables.
map() doesn’t immediately evaluate all items. Instead, it generates values as needed, making it memory-efficient for large data sets.
So it's "lazy".
my_list_1 = [10, 20, 30]
map_iterator_1 = map(lambda x: x**2, my_list_1)
for result in map_iterator_1:
print(result)
Output:
100
400
900
Please notice that we used lambda function here to make code more clear and compact.
The map() function returns an iterator rather than a list. This iterator can be converted to a list by wrapping it in list(map_iterator).
However, iterating over it directly, as shown, is often more memory-efficient.
In following example, we will use normal function that accepts arguments from two iterables.
my_list_1 = [10, 20, 30]
my_range = range(0, 9)
def combine_and_convert_to_string(number_1: int, number_2: int) -> str:
return str(f"{number_1} and {number_2}")
map_iterator_2 = map(combine_and_convert_to_string, my_list_1, my_range)
for result in map_iterator_2:
print(result)
Output:
10 and 0
20 and 1
30 and 2
Please notice that only 3 elements were inside of map_iterator_2. That is because map() stops when the shortest iterable is exhausted.
If you would like to combine several iterables to pass them to map() you should consider using chain() function.
Key Points to Remember
-
Lazy Evaluation:
map()returns a lazy iterator, meaning elements are only computed as needed. -
Multiple Iterables: You can pass multiple iterables to
map(), but it will stop processing once the shortest iterable is exhausted. -
Lambda Functions for Simplicity: Lambda functions are often used with
map()for shorter code.
I hope you found this helpful! If you have any feedback, questions or requests, please reach out to me through Contact page!