Is the single underscore "_" a built-in variable in Python?

python

Solution

In the standard Python REPL, `_` represents the last returned value -- at the point where you called `len(_)`, `_` was the value `'abc'`.

For example:

>>> 10
10
>>> _
10
>>> _ + 5
15
>>> _ + 5
20

This is handled by `sys.displayhook`, and the `_` variable goes in the `builtins` namespace with things like `int` and `sum`, which is why you couldn't find it in `globals()`.

Note that there is no such functionality within Python scripts. In a script, `_` has no special meaning and will not be automatically set to the value produced by the previous statement.

Also, beware of reassigning `_` in the REPL if you want to use it like above!

>>> _ = "underscore"
>>> 10
10
>>> _ + 5

Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    _ + 5
TypeError: cannot concatenate 'str' and 'int' objects

This creates a global variable that hides the `_` variable in the built-ins. To undo the assignment (and remove the `_` from globals), you'll have to:

>>> del _

then the functionality will be back to normal (the `builtins._` will be visible again).

Problem

I don't understand what this single underscore means. Is it a magic variable? I can't see it in locals() and globals(). ``` >>> 'abc' 'abc' >>> len(_) 3 >>> ```

Original source

Related problems