In many symbolic math systems, such as Matlab or Mathematica, you can use a variable like Ans or % to retrieve the last computed value. Is there a similar facility in the Python shell?
Asked
Active
Viewed 5.4k times
182
poke
- 339,995
- 66
- 523
- 574
Edward Z. Yang
- 25,702
- 16
- 78
- 108
-
13Even in Python the last answer will be 42. – Tomalak Oct 14 '08 at 04:40
-
342? Everyone missed the opportunity for a Prior Incantato reference! – amindfv Sep 26 '11 at 02:44
-
1[in]>>> _1 [out]>>> 42? Everyone missed the opportunity for a Prior Incantato reference! – gregory Feb 28 '19 at 19:22
3 Answers
276
Underscore.
>>> 5+5
10
>>> _
10
>>> _ + 5
15
>>> _
15
Mark Cidade
- 96,194
- 31
- 221
- 232
-
26It only works in the interactive shell, though. Don't rely on it for scripts. – John Fouhy Oct 14 '08 at 04:54
-
11Additionally, it doesn't work if the variable `_` has been previously assigned. It's not uncommon, as this symbol is also used for throwaway variables (see https://stackoverflow.com/questions/5893163/what-is-the-purpose-of-the-single-underscore-variable-in-python) – Jul 05 '17 at 08:06
-
5Yay, the final piece. With this I can use interactive python as my calculator. – Jaakko Aug 09 '19 at 10:18
99
Just for the record, ipython takes this one step further and you can access every result with _ and its numeric value
In [1]: 10
Out[1]: 10
In [2]: 32
Out[2]: 32
In [3]: _
Out[3]: 32
In [4]: _1
Out[4]: 10
In [5]: _2
Out[5]: 32
In [6]: _1 + _2
Out[6]: 42
In [7]: _6
Out[7]: 42
And it is possible to edit ranges of lines with the %ed macro too:
In [1]: def foo():
...: print "bar"
...:
...:
In [2]: foo()
bar
In [3]: %ed 1-2
Peter Hoffmann
- 52,690
- 14
- 73
- 58
-
5Found `__` and `___` by chance as well in 1.2.1. – Ciro Santilli Путлер Капут 六四事 Jul 08 '16 at 12:56
19
IPython allows you to go beyond the single underscore _ with double (__) and triple underscore (___), returning results of the second- and third-to-last commands.
Alternatively, you can also use Out[n], where n is the number of the input that generated the output:
In [64]: 1+1
Out[64]: 2
...
In [155]: Out[64] + 3
Out[155]: 5
For more info, see https://jakevdp.github.io/PythonDataScienceHandbook/01.04-input-output-history.html .
Jan Kukacka
- 1,098
- 1
- 12
- 28