Ahto
Ahto

Reputation: 11

In the Python interactive interpreter, is there any way to refer to the results of the last command?

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?

Upvotes: 0

Views: 78

Answers (2)

Chris Drake
Chris Drake

Reputation: 393

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

Upvotes: 0

BrenBarn
BrenBarn

Reputation: 251498

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.

Upvotes: 7

Related Questions