Sub topic 5
Reusing the last result with _
Prerequisites
This chapter assumes you can already start the interactive shell and read its output. It also assumes you know that the shell echoes the value of an expression. You need basic Python: variables, function calls, and the idea that a function can return None. The examples work in Python 3 in the standard shell, and they behave the same in the newer shell that ships with Python 3.13.
What `_` is
When you evaluate an expression at the >>> prompt, the shell prints the result. It also saves that result under the name _ (a single underscore). The next line can use _ as if it were a variable.
>>> 2 + 3
5
>>> _ * 10
50
>>> _
50Each echoed value replaces the previous one. After _ * 10 printed 50, the name _ refers to 50, not 5.
This is useful when you run a call and then decide you want to do more with its result. You don't have to retype the call or scroll back to assign it to a variable.
>>> "a,b,c".split(",")
['a', 'b', 'c']
>>> len(_)
3
>>> import math
>>> math.sqrt(2)
1.4142135623730951
>>> round(_, 3)
1.414
>>> _ * 2
2.828Which results are stored
The shell stores a value in _ only when it echoes it. Three rules follow from that.
- Assignments don't change
_. An assignment is a statement, not an expression, so nothing is echoed. Noneis never stored. The shell skipsNone, so_keeps its previous value.- Exceptions don't change
_. A failed statement produces a traceback and no value.
>>> 10
10
>>> y = 99
>>> _
10
>>> print("hi")
hi
>>> _
10
>>> int("abc")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'abc'
>>> _
10print("hi") writes text and returns None. Since the shell doesn't echo None, _ still holds 10.
The same applies to any method that returns None, such as list.sort().
| Input at the prompt | Echoed? | Changes `_`? |
|---|---|---|
| `3 + 4` | yes, `7` | yes, becomes `7` |
| `x = 3 + 4` | no | no |
| `print("a")` | no (it writes text itself) | no |
| `[1, 2].append(3)` | no (returns `None`) | no |
| `[]` | yes, `[]` | yes, becomes `[]` |
| `0`, `False`, `""` | yes | yes |
| `1 / 0` | traceback | no |
Falsy values such as 0 and "" are stored. The shell only checks whether the value is None, not whether it is truthy.
How it works: the display hook
The shell does not treat _ specially in the grammar. The mechanism is a function called sys.displayhook. The interpreter calls it with the value of every expression statement it runs in interactive mode. The default hook does roughly this:
- If the value is
None, return without doing anything. - Set
builtins._ = None. - Print the
repr()of the value, followed by a newline. - Set
builtins._ = value.
Because _ lives in the builtins module, you can read it from anywhere in the session without importing anything. Because step 2 comes before step 3, a value whose repr() raises an exception leaves _ as None.
You can see this by replacing the hook. The replacement below prints values in its own format and never stores them.
>>> import sys
>>> def hook(value):
... if value is not None:
... print("got", value)
...
>>> sys.displayhook = hook
>>> 1 + 1
got 2
>>> sys.displayhook = sys.__displayhook__
>>> 5 * 5
25
>>> _
25Restoring sys.__displayhook__ brings back the default behavior. Customizing the hook is rarely needed, but it shows that _ is a side effect of the hook and not a language feature. That also explains why _ exists only in interactive mode. A script never calls the hook, so 2 + 3 on a line of a .py file computes a value and discards it.
The value is a reference, not a copy
_ points at the same object that was echoed. If the object is mutable, changes made through _ are visible through any other name for it.
>>> [3, 1, 2]
[3, 1, 2]
>>> _.sort()
>>> _
[1, 2, 3]_.sort() sorts the list in place and returns None. Nothing is echoed, so _ is not replaced, and it now refers to the sorted list.
Save a result under a real name before you run anything that might overwrite _:
>>> sorted({"b": 2, "a": 1})
['a', 'b']
>>> keys = _
>>> keys
['a', 'b']
>>> 100
100
>>> keys
['a', 'b']
>>> _
100Expressions inside blocks also set `_`
Echoing applies to every expression statement the shell compiles, including those inside a loop body. Each one is echoed and stored as it runs.
>>> for n in range(3):
... n * 2
...
0
2
4
>>> _
4In a script, the same loop would print nothing. This catches people out when they copy a loop from the shell into a file and expect the same output. Wrap the expression in print() if you want it to appear in both places.
Shadowing `_` and how to undo it
_ is a normal name stored in builtins. If you assign to _ yourself, you create a global variable in your session, and Python finds that one first. The shell keeps updating builtins._, but you no longer see it.
>>> _ = "mine"
>>> 7 * 6
42
>>> _
'mine'
>>> del _
>>> _
42Deleting your global _ uncovers the built-in one again, which still holds the latest echoed value. The echo 42 still appeared because the hook ran normally.
Several common idioms assign to _ and trigger this problem:
for _ in range(3):uses_as a throwaway loop variable.first, _ = pairuses_to ignore a tuple element.import gettext; _ = gettext.gettextfollows the translation convention, where_("text")marks a string for translation.
If _ stops updating in a session, one of these has probably run. Type del _ and try again. If del _ raises NameError, you have no shadowing global, and the problem is something else, such as the value being None.
Before anything has been echoed
In a fresh session builtins._ does not exist yet. The first use fails:
>>> _
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name '_' is not definedAfter the first non-None result, the name exists. After that, _ is never undefined again unless you shadow it and delete your own copy in an unusual way.
Memory and large results
Because _ holds a reference, the last echoed object stays alive until you echo something else. If you evaluate an expression that builds a very large list, _ keeps it in memory. Echo a small value, such as 0, to release it. Another short expression such as None won't work, since None is not stored.
>>> big = list(range(10_000_000))
>>> len(big)
10000000
>>> list(range(10_000_000))[:3]
[0, 1, 2]
>>> _
[0, 1, 2]In the last example only the slice is echoed, so the ten-million-item list is freed once the expression finishes. Slicing before echoing keeps output readable and avoids holding the large object.
Related behavior in other shells
The standard shell keeps only one previous result. IPython and Jupyter keep more: _, __ (two underscores), and ___ hold the last three results, and Out[n] holds every result by number. IDLE behaves like the standard shell. If a tutorial or answer you find online uses __ or Out, it assumes a different shell. In the standard shell, those names are not defined.
Practical guidance
- Use
_for quick, throwaway chaining where you know the next line will run immediately. - Assign to a real name when you need the value after more than one more statement. Any later non-
Noneecho replaces_. - Don't rely on
_in code you plan to save. It doesn't exist outside the interactive shell. - Avoid using
_as a variable in a session where you want to chain results. - If a result seems missing, check whether it was
None. That is the most common reason_doesn't change.
Exercise
You run these lines in a fresh shell. What does the final line echo, and why? >>> 8 8 >>> x = + 1 >>> print(x) 9 >>>
Show answer
It echoes 8. The assignment x = _ + 1 is a statement, so it echoes nothing and doesn't change _. print(x) returns None, which the shell never stores. The last echoed value was 8, so _ still holds 8.
Exercise
A session has the lines below. Why does the last line show 'ignored' and not 12, and what single command fixes it?
>>> a, = ("kept", "ignored")
>>> 3 * 4
12
>>>
'ignored'
Show answer
The tuple unpacking assigned "ignored" to a global variable named _. That global shadows builtins._, which the display hook still updated to 12. Running del _ removes the global, and the next _ shows 12.
Exercise
Predict the output of each line, then explain why a script containing the same loop would print nothing. >>> for n in range(1, 4): ... n ** 2 ... >>> _
Show answer
The loop echoes 1, 4, and 9 on separate lines, because each expression statement inside the block is echoed in interactive mode. The final _ echoes 9, the last stored value. A script never calls sys.displayhook, so the expression n ** 2 is computed and thrown away. You would need print(n ** 2) to see output.