Use of "_" in a interpreter/code editor

Hello Python people,
I am wondering why I can use the “_” in an interpreter like anaconda prompt, but not in Atom?

in an interpreter:

6 + 9
>>> 15
_ + 10

in Atom:


NameError: name ‘_’ is not defined

Aside from a very quick and dirty interactive session it’s a very bad idea to try and use _ as a variable name (whether or not you think it’s useful there is your own business). I’m not even sure _ has a real meaning outside of an interactive session. It’s used for dumping things that you don’t want the interpreter to remember. If you actually ran it as a script I would very much expect this to break.

Edit: Some quick tests and it seems like _ is a valid variable name (a bad one perhaps but a valid name). However it has nothing to do with the last output like _ does in an interactive session.


The only usage I’ve ever encountered, and do myself, is in a loop where the variable is ignored.

for _ in range(n):
    # do something repeatedly

Applies also to comprehensions:

array  = [0 for _ in range(n)]

will be a list of n length filled with zeroes.


Not very readable, but totally legit:

def _(__, ___):
    return __ + ___
print(_(5, 4)) #Output: 9

That’s the main use I’m familiar with. I tried a couple of scripts using it as a regular variable name which seems to work (that assignment is not instantly forgotten, it’s a valid identifier)- 2. Lexical analysis — Python 3.10.0a6 documentation

I think @elmn77 way referring to the interactive interpreter you can get by simply running python without arguments (or ipython etc.). Some of these use _ to refer to the last object returned in an interactive session (like the original example). I assume they ran a script with atom (instead of an interactive session) in which case _ doesn’t have a special meaning like it does for the interactive session.


That pattern could be applied in a function factory to save on verbosity, one imagines.

    return _
1 Like

Yes, I tought it is because in the prompt, the variable is stock in the cache memory, while in Atom, since there s no variable declaration, it can’t associate the “_” with a value.

I found that, who 's super conveniant:

lst = [1, 47, 25, 801, 3]
a, *_ ,b = lst
>>> 1
>>> 3

Thanks all for your answers.