Thursday, June 21, 2012

IDKTAP #1: Omitting "print" in the Python shell

"I Didn't Know That About Python" covers surprising little things I've learned about Python. Nothing earthshattering. First in a series. 

Most Python hackers have spent a lot of time exploring in the Python interactive shell, and therefore know that Python obligingly prints the results of expressions for you when they return a value:

>>> 2+2
4

You might be forgiven for assuming Python is just printing the result of the last expression it evaluated. But in fact, it's printing the result of any and all expressions that you don't do anything else with.

>>> 2+2; 3+3
4
6
>>> for x in xrange(5): x
...
0
1
2
3
4

This behavior, though subtly different from what you might expect, lets you omit print much of the time in Python interactive mode, saving you precious fractions of a second each time. Because life is too short to spend it typing print!

Thanks to Joel Cornett for pointing this out in a comment on a StackOverflow answer.

No comments:

Post a Comment