Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python map function iteration

Tags:

python

map

results 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 definition like this:

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

Normal iteration on results does behaves like this:

>>> 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 implicit iteration with map, results in this behaviour:

>>> 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: Why does map function produce the additional iteration?

like image 743
Rishabh Sagar Avatar asked May 25 '13 14:05

Rishabh Sagar


Video Answer


1 Answers

map applies a function to each element of the iterable and the result of that is stored back in a list (or map object in Python 3). So the [None, None, None, None] part is the return value of the map function. You won’t see this when you execute a script, but you can also get rid of it in IDLE by just assigning it to a value:

>>> _ = map(pr, results)

Note though, that the construction of the result list (at least in Python 2) has some impact, so if you don’t need the result, you’re better off not using map in this case.

like image 121
poke Avatar answered Sep 28 '22 04:09

poke