Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why map(print, a_list) doesn't work?

For a normal function, map works well:

def increment(n):
    return n+1
l = [1, 2, 3, 4, 5]
l = map(increment, l)
print l
>>> [2, 3, 4, 5, 6]

However, if it's print being put inside the map function:

l = [1, 2, 3, 4, 5]
l = map(print, l)
print l

python will complain:

l = map(print, l)
            ^
SyntaxError: invalid syntax

What makes print special? Doesn't print(x) also a valid function call? The above code are tested under python 2.7.

like image 818
clwen Avatar asked Aug 01 '12 21:08

clwen


People also ask

What does map function do in Python?

Map in Python is a function that works as an iterator to return a result after applying a function to every item of an iterable (tuple, lists, etc.). It is used when you want to apply a single transformation function to all the iterable elements. The iterable and function are passed as arguments to the map in Python.


2 Answers

In Python 2.x, print is a statement, not a function. If you try this in Python 3.x it will work.

In Python 2.x, you can say print(x) and it is not a syntax error, but it isn't actually a function call. Just as 1 + (3) is the same as 1 + 3, print(x) is the same as print x in Python 2.x.

In Python 2.x you can do this:

def prn(x):
    print x

Then you can do:

map(prn, lst)

and it will work. Note that you probably don't want to do lst = map(prn, lst) because prn() returns None, so you will replace your list of values with a same-length list of just the value None.

EDIT: Two other solutions for Python 2.x.

If you want to completely change the behavior of print, you can do this:

from __future__ import print_function

map(print, lst)

This makes print into a function just as it is in Python 3.x, so it works with map().

Or, you can do this:

from pprint import pprint

map(pprint, lst)

pprint() is a function that prints things and it is available as a built-in. I'm not exactly sure how it is different from the default print (it says it is a "pretty-print" function but I'm not sure how exactly that makes it different).

Also, according to the PEP 8 standard, it is non-recommended to use l as a variable name, so I am using lst instead in my examples.

http://www.python.org/dev/peps/pep-0008/

like image 97
steveha Avatar answered Sep 16 '22 19:09

steveha


A better way to map print in 2.x would be to do

from __future__ import print_function
like image 42
Jakob Bowyer Avatar answered Sep 19 '22 19:09

Jakob Bowyer