Today we’ll see how to use the underscore sign to retrieve the last result, or, to be more precise, the most recent output. This only works in interactive mode.
A Simple Example of the Last Result Variable
So, we can use the underscore sign to retrieve the most recent output like so:
>>> 4 + 5
9
>>> _
9
You can use the underscore sign in your code. It’ll be just replaced by the last result:
>>> 10 * 3
30
>>> 3 * _ + _ # same as 3 * 30 + 30
120
Other Data Types
The underscore sign is a variable to which the last result is assigned. In the examples above it was used to replace numbers, integers to be more precise. But it would work exactly the same for any other type of number, be it a floating point number or a complex number for example. What’s more, the underscore variable is not limited to numeric results. It can be used to retrieve the last result regardless of its type. In the examples below you can see how it can be used for some other data types.
Here are some examples with other data types: strings, lists, dictionaries and booleans. In the first example the underscore variable is used to retrieve the last result which is a string obtained by concatenating and repeating some other strings. What’s more interesting, you can even use it in formatted text, which you can see in the f-string below. It behaves just like any other variable.
Then there’s a list, which is obtained by concatenating two other lists. As this list is the last result, you can use the underscore variable to represent it. Here you can see how you can use a method on it just as if it were a normal list (which it actually is).
In the dictionary example the last result is a dictionary, so we can access its elements by key.
Finally, the underscore variable can also stand for a boolean value if such a value is the last result.
# string
>>> 's' + 'o' * 5 + ' good'
'sooooo good'
>>> print(f"The weather was {_}!")
The weather was sooooo good!
# list
>>> [2, 4, 6] + [8, 10]
[2, 4, 6, 8, 10]
>>> _.append(12)
>>> _
[2, 4, 6, 8, 10, 12]
# dictionary
>>> dict(zip(['A', 'B', 'C'], ['a', 'b', 'c']))
{'A': 'a', 'B': 'b', 'C': 'c'}
>>> if 'D' not in _:
... _['D'] = 'd'
...
>>> _
{'A': 'a', 'B': 'b', 'C': 'c', 'D': 'd'}
# bool
>>> 2 + 2 == 4
True
>>> _ and not _ # same as True and not True
False
As mentioned before, we can use the underscore sign only in interactive mode.
Here’s the video version: