4

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?

Ed Stretton
  • 41
  • 1
  • 3

1 Answers1

4

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
Community
  • 1
  • 1
Maxim Belkin
  • 138
  • 1
  • 6