Why is parenthesis in print voluntary in Python 2.7?

Hubro picture Hubro · May 31, 2011 · Viewed 88.3k times · Source

In Python 2.7 both the following will do the same

print("Hello, World!") # Prints "Hello, World!"

print "Hello, World!" # Prints "Hello, World!"

However the following will not

print("Hello,", "World!") # Prints the tuple: ("Hello,", "World!")

print "Hello,", "World!" # Prints the words "Hello, World!"

In Python 3.x parenthesis on print is mandatory, essentially making it a function, but in 2.7 both will work with differing results. What else should I know about print in Python 2.7?

Answer

user166390 picture user166390 · May 31, 2011

In Python 2.x print is actually a special statement and not a function*.

This is also why it can't be used like: lambda x: print x

Note that (expr) does not create a Tuple (it results in expr), but , does. This likely results in the confusion between print (x) and print (x, y) in Python 2.7

(1)   # 1 -- no tuple Mister!
(1,)  # (1,)
(1,2) # (1, 2)
1,2   # 1 2 -- no tuple and no parenthesis :) [See below for print caveat.]

However, since print is a special syntax statement/grammar construct in Python 2.x then, without the parenthesis, it treats the ,'s in a special manner - and does not create a Tuple. This special treatment of the print statement enables it to act differently if there is a trailing , or not.

Happy coding.


*This print behavior in Python 2 can be changed to that of Python 3:

from __future__ import print_function