6

I just found something weird in the Python interpreter. Let me show you:

$ python
Python 2.7.1+ (r271:86832, Apr 11 2011, 18:13:53) 
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> _
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name '_' is not defined
>>> 5 + 4
9
>>> _
9
>>> 'Hello world'
'Hello world'
>>> _
'Hello world'
>>> type(3.5)
<type 'float'>
>>> _
<type 'float'>

You can try this in your interpreter; there are no tricks at work here!

Is the result of the last executed line being assigned to a variable named _?

Does anybody know something about it? Is there any documentation about it? In which situation could it be useful?

7
  • 2
    I thought everybody knew (and used) that...
    – JBernardo
    Jan 31, 2012 at 1:37
  • 3
    search for underscore and python at stackoverflow Jan 31, 2012 at 1:40
  • 2
    I think that was really unfair ... Jan 31, 2012 at 1:47
  • 3
    Well, it's not really a question. SO is a question and answer site. If you had asked "Where do I find the implementation of the feature _ in the Python interpreter?" or something similar, it might have survived.
    – sarnold
    Jan 31, 2012 at 1:55
  • 1
    Well, I voted to close as exact duplicate of stackoverflow.com/questions/1538832/… so I'm not sure why my name's in the list for 'closed as not a real question'
    – wim
    Jan 31, 2012 at 1:58

4 Answers 4

9

Take a look here Reserved identifiers python.

The special identifier _ is used in the interactive interpreter to store the result of the last evaluation; it is stored in the builtin module.

This behavior can be found on haskell's interactive environment ghci also. Here instead of _ use it.

Prelude> 2+2
4
Prelude> it
4
3

It's useful when exploring in the interactive interpreter, when you forgot to assign a name to some returned object, you can grab a reference to it using x = _. Note that in ipython you also have __ for the second-to-last returned, and ___ is the third-to-last.

0
0

This isn't a big secret (for example, you can find it mentioned in Code Like a Pythonista) but true, it's not well known. It could be useful when you're doing a lot of work at the command line.

0

Per What is the purpose of the single underscore "_" variable in Python?

There are three main uses for _. One is "real" (the usage you discovered), and the other two are conventions.

Interesting... I never knew!

1

Not the answer you're looking for? Browse other questions tagged or ask your own question.