tdolydong
tdolydong

Reputation: 848

what do _ and __ mean in PYTHON

When I input _ or __ in the python shell I get values returned. For instance:

>>> _
2
>>>__
8

What is happening here?

Upvotes: 12

Views: 8897

Answers (4)

lmiguelvargasf
lmiguelvargasf

Reputation: 69903

According to this, in iPython:

  • _ (a single underscore): stores previous output, like Python’s default interpreter.
  • __ (two underscores): next previous output.

You can also reference previous inputs and outputs depending on the line they are by:

Input: _iX where X is the input line number

Ouput: _X where X is the output line number

Examples:

_

In [1]: 9 * 3
Out[1]: 27

In [2]: _ 
Out[2]: 27

__

In [1]: 9 * 3
Out[1]: 27

In [2]: 4 * 8
Out[2]: 32

In [3]: __
Out[3]: 27

_iX

In [1]: x = 10

In [2]: y = 5

In [3]: _i1
Out[3]: u'x = 10'

_X

In [1]: x = 10

In [2]: y = 4

In [3]: x + y
Out[3]: 14

In [4]: _3
Out[4]: 14

Upvotes: 2

Martin
Martin

Reputation: 2230

If you are using IPython then the following GLOBAL variables always exist:

  • _ (a single underscore): stores previous output, like Python’s default interpreter.
  • __ (two underscores): next previous.
  • ___ (three underscores): next-next previous.

Read more about it from IPython documentation: Output caching system.

Upvotes: 16

kojiro
kojiro

Reputation: 77137

In Python it means what you tell it to mean. Underscores are valid characters in a name. (However, if you are using IPython see Martin's fine answer.)

Python 2.7.5 (default, Aug 25 2013, 00:04:04) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin
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
>>> _=2
>>> _
2
>>> __
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name '__' is not defined
>>> __=3
>>> __
3

That said, they do have some special semantics. Starting a name with a single underscore doesn't do anything programmatically different, but by convention it tells you the name is intended to be private. But if you start a name with two underscores the interpreter will obfuscate it.

>>> class Bar:
...   _=2
...   __=3
...   _x=2
...   __x=3
... 
>>> y=Bar()
>>> y._
2
>>> y.__
3
>>> y._x
2
>>> y.__x
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: Bar instance has no attribute '__x'
>>> dir(y)
['_', '_Bar__x', '__', '__doc__', '__module__', '_x']
>>> y._Bar__x
3

Upvotes: 3

BartoszKP
BartoszKP

Reputation: 35901

Theoretically these are just ordinary variable names. By convention, a single underscore is used as a don't care variable. For example, if a function returns a tuple, and you're interested only in one element, a Pythonic way to ignore the other is:

_, x = fun()

In some interpreters _ and __ have special meanings, and store values of previous evaluations.

Upvotes: 6

Related Questions