Python map function iteration

the result is a nested list and looks like this:

>>> results [[1, 2, 3, 'a', 'b'], [1, 2, 3, 'c', 'd'], [4, 5, 6, 'a', 'b'], [4, 5, 6, 'c', 'd']] 

pr is a function with the definition:

 >>> def pr(line): ... print line 

Normal iteration according to the results behaves as follows:

 >>> for result in results: ... pr(result) ... [1, 2, 3, 'a', 'b'] [1, 2, 3, 'c', 'd'] [4, 5, 6, 'a', 'b'] [4, 5, 6, 'c', 'd'] 

But an implicit iteration with a map leads to this behavior:

 >>> map(pr, results) [1, 2, 3, 'a', 'b'] [1, 2, 3, 'c', 'd'] [4, 5, 6, 'a', 'b'] [4, 5, 6, 'c', 'd'] [None, None, None, None] 

My question is : Why does the map function create an additional iteration?

+6
source share
3 answers

map applies a function to each element of the iterable, and the result is stored in a list (or map object in Python 3). Thus, the [None, None, None, None] is the return value of the display function. You won't see this when you run the script, but you can also get rid of it in IDLE by simply assigning it to a value:

 >>> _ = map(pr, results) 

Note that building a list of results (at least in Python 2) has a certain effect, so if you don't need a result, you'd better not use map in this case.

+6
source

map in Python 2 returns a list containing all the return values โ€‹โ€‹of the function you are passing. Your pr function returns None (implicitly, falling from the end). Thus, the result of map will be a list filled with None s, one for each object in the iterable that you are passing. This is automatically printed by the interactive interpreter, since you did not assign it to a variable - this is the last line that you see.

You can see this more clearly when you assign it to a variable:

 >>> a = map(pr, results) [1, 2, 3, 'a', 'b'] [1, 2, 3, 'c', 'd'] [4, 5, 6, 'a', 'b'] [4, 5, 6, 'c', 'd'] >>> a [None, None, None, None] 

Note that using map when you don't care about this result usually makes your code more difficult to read; and use it for side effects even more. In both cases, it is preferable to write an explicit loop.

+6
source

[None, None, None, None] is the result of calling map , which is automatically printed in the Python interpreter console.

+3
source

Source: https://habr.com/ru/post/945837/


All Articles