map on many values
Now imagine you have a very long list. I know this is not such a long list, but I trust you can imagin a long list of numbers. We would like to run
some function on each element and then iterate over the results, but what if at one point in the iteration we decide to break
out of the loop?
import sys
def double(n):
print(f"double {n}")
return 2 * n
numbers = [1, 4, 2, -1, 23, 12, 5, 6, 34, 143123, 98, 213]
double_numbers = map(double, numbers)
print(double_numbers)
for num in double_numbers:
print(num)
if num > 42:
break
print()
print(sys.getsizeof(numbers))
print(sys.getsizeof(double_numbers))
<map object at 0x7fe5c5270d68>
double 1
2
double 4
8
double 2
4
double -1
-2
double 23
46
160
56
You can see that it did not need to waste time calculating the doubles of all the values, as it was calculating on-demand. You can also see that the object returned
from map
takes up only 56 bytes. Regardless of the size of the original array.