0

in this post it is explained, how to use the result of a previous code execution by using _, e.g.

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

The question is inspired by languages like Mathematica, where you can easily call the result of the last line.

I notices, that this example does not work when you execute it all at ones, e.g.

5+5
_+5

Is there a corresponing way to calculate without defining new variables each time?


Edit: The role of _ has been understood. The question is, wether there is (can be/ can't be) a corresponding statement that reads the result of the last line within the same execution.

Uwe.Schneider
  • 1,112
  • 1
  • 15
  • 28

1 Answers1

3

This behavior of _ is only available in REPL. _ holds the output of that the last expression evaluated to. It should be noted, if the previous expression produced a TRACEBACK, _ will hold the last valid output. You could also chain _ upto three times (in IPython), to go fetch the 3rd last output:

>>> 5
5
>>> 6
6
>>> 7
7
>>> ___
5
>>> __
7
>>> _
7

If you use it in actual scripts, you can treat it _ as a variable name (not recommended, if you plan to use the variable), for example:

_ = 10
print(_)

# will print 10

But the behavior you get at REPL can't be emulated in an actual script.

Sayandip Dutta
  • 15,602
  • 4
  • 23
  • 52