Python 3's map
returns an iterator (the map
object you see in your output). This iterator is lazy, it only does the work of applying the function to one value from the input iterator at a time, in order to produce one output value. This is convenient when the input is also a lazy iterator, and the output can be consumed one value at a time.
Consider this code:
with open(some_file) as f_in, open(some_file + ".out", "w") as f_out:
f_out.writelines(map(line_transform_func, f_in))
This opens two files, one for reading and one for writing. It then reads in lines from the input file, performs some kind of transform on them, then writes them to the output file. Since files are lazy, there's no need for the whole contents of the input file to be read into memory at once. Instead, you only need enough memory to read one line at a time. Similarly, since map
returns a lazy iterator, the transformed lines will be produced one line at a time, and the writelines
method can write each one out to disk before requesting the next one. This is very important if the files are huge (multiple gigabytes, maybe more than can fit in memory at one time).
Another advantage of map
being a lazy iterator is that it doesn't need to run its function on all the input if you stop iterating on the output early. For example, lets say you had an expensive computation to do on a large input sequence, but you only need to do it until you find the first output that meets some criteria. You could use map
and a loop with a break
statement to stop iterating as soon as you found the value you needed:
for value in map(some_expensive_operation, input_values):
if some_criteria(value):
break
If map
produced a list, it would need to apply the expensive operation to all the values from the input up front, before the iteration could happen.
(Note that I would not normally write like either of these examples using map
at all, I'd just write an explicit for
loop and apply the function myself, but map
works fine too.)
If you're not familiar with Python iterators, I strongly recommend that you read up on them. They're a big part of how Python works, and understanding them (and how to create and use new lazy ones, e.g. with generator functions) is a big part of becoming a more skilled Python programmer.