Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does map(print, x) return "None" value list?

In Python 3.5, the code

>>> T = map(print, [1, 2, 3])
>>> type(T)
<class 'map'>

returns a map object. I would expect this map object T to contain the numbers 1, 2 and 3; all on separate lines. In actuality, this does happen. The only problem is that it also outputs a list of Nonevalues the same length as the input list.

>>> list(T)
1
2
3
[None, None, None]
>>> 

This is repeatable for any input I use, not just the arbitrary integer list shown above. Can anyone explain why this happens?

like image 806
Ed Stretton Avatar asked Sep 17 '25 22:09

Ed Stretton


1 Answers

See also:
https://stackoverflow.com/a/7731274
https://stackoverflow.com/a/11768129
https://stackoverflow.com/a/42399676

Each None that you see is what print function returns. To understand what map does, try the following code:

>>> T = map(lambda x: x**2, [1, 2, 3])
>>> t = list(T)
>>> print(t)
[1, 4, 9]

When you use print instead:

>>> T = map(print, [1, 2, 3])
>>> t = list(T)
1
2
3
>>> print(t)
[None, None, None]

This is not surprising, because:

>>> a = print("anything")
anything
>>> print(a)
None
like image 182
Maxim Belkin Avatar answered Sep 20 '25 11:09

Maxim Belkin