The Python interpreter assigns the last value of the _ expression.
This behavior is limited only by the REPL interpreter and is intended to aid in interactive coding sessions:
>>> import math >>> math.pow(3.0, 5) 243.0 >>> result = _ >>> result 243.0
The standard Python interpreter is long so as not to trample on user-defined values; if you yourself assign something else _ , then the interpreter will not overwrite it (technically speaking, the variable _ is an attribute of __builtin__ , your own assignments are "regular" globals). However, you are not using the standard Python interpreter; you are using IPython and this interpreter is not so careful.
IPython explicitly describes this behavior :
The following GLOBAL variables always exist (so do not overwrite them!):
[_] (one underscore): saves the previous output, for example the default interpreter Pythons.
[...]
Outside the Python interpreter, _ is used by default as the name of the translated text function (see gettext module ; external tools look for this function to extract the translatable strings).
In loops, using _ as the destination, readers read your code that you will ignore this value; for example [random.random() for _ in range(5)] to generate a list of 5 random float values.
Martijn Pieters Jul 10 '13 at 20:30 2013-07-10 20:30
source share