5

I saw somewhere about the _ character being used in Python like:

print _

Can somebody help me explain what it does?

Salil Navgire
  • 191
  • 1
  • 1
  • 10

3 Answers3

18

In the interactive interpreter, _ always refers to the last outputed value:

>>> 1 + 1
2
>>> print _
2
>>> 2 + 2
4
>>> print _
4
>>>

In normal Python1 code however, _ is just a typical name. You can assign to it as you would any other:

_ = 3
print _
# Output: 3

Although I wouldn't recommend actually doing this because _ is a terrible name. Also, it is used by convention to mean a name that is simply a placeholder. An example would be:

a, _, b = [1, 2, 3]

which uses _ to mean that we are not interested in the 2. Another example is:

for _ in range(10):
    function()

which means that we are not using the counter variable inside the loop. Instead, we only want Python to call function ten times and need the _ to have valid syntax.


1By "Python", I mean CPython, which is the standard flavor of the language. Other implementations may choose to do things differently. IPython for example has this to say about underscore-only names:

The following GLOBAL variables always exist (so don’t overwrite them!):

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

Source: http://ipython.org/ipython-doc/rel-0.9.1/html/interactive/reference.html#output-caching-system

1

It's just another variable name, that is typically used for three very different things:

In the Python interactive shell, _ is the value of the last expression that was entered:

>>> 3 + 3
6
>>> _ == 6
True

It is used to indicate that some variable is just there because it needs to be and won't be used any further:

instance, _ = models.MyModel.objects.get_or_create(name="Whee")

(here, get_or_create returned a tuple with two elements, only one of which is going to be used by us).

The function used for translating strings (often ugettext) is often locally renamed to _() so that it takes up as little screen space as possible:

 from django.utils.translation import ugettext as _

 print(_("This is a translatable string."))
RemcoGerlich
  • 30,470
  • 6
  • 61
  • 79
0

'_'is a legal python character just like most other Programming Languages. I think MATLAB is the exception where you cannot use that for any MATLAB file names. I know because I tried it in the past and it failed. Don't know if this has been changed since R2014b. In python, the best examples are __init__, __self__, __str__, __repr__, etc.

Rather than asking questions and having confusions in your mind, just type it and see what happens. You won't break anything :D. Open Python IDLE, and press CTRL+. you will see lots of Python native variables and functions named with _ or even __. I quite liked the variable assignment example provided by @iCodez here :)

ha9u63a7
  • 6,233
  • 16
  • 73
  • 108