0

I wonder why 'print' can not be used in python map function? I assume print is also a function so this should work as map works on functions as documentation: map(function, iterable, ...)

a=[1,2,3,4]
map(print,a)
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
curious
  • 169
  • 9

3 Answers3

2

You are not iterating over the map() object, so no function calls are made. map() does not immediately apply the calls; only as you drab results from the iterator, are elements from the input sequence drawn and have the print() function applied.

If you looped over the map() object the code works; for example, by using the list() call:

>>> a = [1, 2, 3, 4]
>>> it = map(print, a)
>>> list(it)
1
2
3
4
[None, None, None, None]
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
1

In you actually can apply print in a map. The print will always return None but that's not really a problem.

The only problem with is that map works lazy: it returns a generator that will only calculate elements if they are needed. In order to get Python to work, you need to materialize the outcome of map somehow. You can for instance do this with list(..):

$ python3
Python 3.5.2 (default, Nov 17 2016, 17:05:23) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> a=[1,2,3,4]
>>> list(map(print,a))
1
2
3
4
[None, None, None, None]

In , print is not a function and thus you cannot provide it to map.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
1

In Python 2, print is not a function so map(print,[]) triggers invalid syntax.

Python 2 workaround would be to use a real function to write to standard output. sys.stdout.write would almost be a candidate, but you have to add a linefeed + string conversion to roughly emulate what print does:

map(lambda x: sys.stdout.write(str(x)+"\n"),a)

It works in python 3 (but map doesn't unless you force iteration)

EDIT: from __future__ import print_function also allows to use print as a function

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219