Skip to content

IPython - IO Caching

IPython automatically caches the inputs you enter and the outputs it produces during a session. This caching system provides convenient ways to refer back to previous commands and results.

IPython stores previous inputs in several ways:

  • In dictionary/list: The In object (behaves like both a list and dict) stores all input commands as strings, indexed by the input cell number. In[1] retrieves the first command, In[2] the second, and so on.
  • _i, _ii, _iii: These variables store the last three input strings (_i is the most recent).
  • _i<n>: You can retrieve the input of a specific cell n using the shortcut _i<n> (e.g., _i3 retrieves the input of In [3]).
  • _ih list: Similar to In, this list holds the input history as strings.
In [1]: greeting = "Hello"
In [2]: name = "IPython"
In [3]: full_message = f"{greeting}, {name}!"
In [4]: print(full_message)
# Output: Hello, IPython!
In [5]: _i # Last input
Out[5]: 'print(full_message)'
In [6]: _ii # Second to last input
Out[6]: 'full_message = f"{greeting}, {name}!"'
In [7]: _i3 # Input from In[3]
Out[7]: 'full_message = f"{greeting}, {name}!"'
In [8]: In[1:4] # Slice of inputs (like a list)
Out[8]: ['greeting = "Hello"', 'name = "IPython"', 'full_message = f"{greeting}, {name}!"']
In [9]: _ih[2] # Accessing history list by index
Out[9]: 'name = "IPython"'

Note: In[0] or _ih[0] usually holds an empty string or session startup information.

IPython also caches the results (outputs) of your commands:

  • Out dictionary: This dictionary stores the output objects, mapping the input cell number to its corresponding result. Commands that don’t produce an output (like assignments) are not stored here.
  • _, __, ___: These variables store the last three output objects (_ is the most recent). This is extremely useful for quickly reusing a result in the next calculation.
  • _<n>: You can retrieve the output of a specific cell n using the shortcut _<n> (e.g., _5 retrieves the output of Out[5]).
  • _oh dictionary: Similar to Out, this dictionary holds the output history.
In [1]: 10 * 2
Out[1]: 20
In [2]: 3 + 5
Out[2]: 8
In [3]: _ + __ # Adds the last output (8) and the second-to-last output (20)
Out[3]: 28
In [4]: list(Out.keys()) # Show which cells produced output
Out[4]: [1, 2, 3]
In [5]: Out[2]
Out[5]: 8
In [6]: _2 # Shortcut for Out[2]
Out[6]: 8
In [7]: x = 100 # No output generated
In [8]: Out.get(7, 'No output') # Cell 7 had no output
Out[8]: 'No output'

These caching mechanisms significantly enhance interactivity, allowing you to avoid re-typing commands or re-running calculations just to access previous results.