0

When I'm using the Python interactive interpreter, I frequently find myself doing this:

>>> a = "starting value"
>>> foo(a)
"something I don't want"
>>> bar(a)
"what I wanted"
>>> a = bar(a)

Is there any way to just do:

>>> bar(a)
"what I wanted"
>>> a = thing_from_before

That is, is there any way to refer to the variable that was printed out by the last command that I ran?

Ahto
  • 1
  • 1

2 Answers2

7

Yes, it is in the variable _:

>>> 2+2
4
>>> _
4

Note that this is not "what was printed", it is the value of the previous expression. So if bar(a) just prints something and doesn't return the value, _ won't help you.

BrenBarn
  • 242,874
  • 37
  • 412
  • 384
  • Thank you! For some reason, I was unable to find this in all of my internet searches. – Ahto Nov 30 '13 at 19:23
0

If you're using IPython instead of the vanilla interpreter, you can use the In and Out dictionaries to refer to arbitrary results from the past:

In [1]: 2 + 2
Out[1]: 4

In [2]: Out[1] + 2
Out[2]: 6

In [2]: Out[1] + 4
Out[2]: 8
Chris Drake
  • 353
  • 1
  • 7