IPython - IO Caching
IPython - Input/Output Caching
Section titled “IPython - Input/Output 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.
Input Caching
Section titled “Input Caching”IPython stores previous inputs in several ways:
Indictionary/list: TheInobject (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 (_iis the most recent)._i<n>: You can retrieve the input of a specific cellnusing the shortcut_i<n>(e.g.,_i3retrieves the input ofIn [3])._ihlist: Similar toIn, 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 inputOut[5]: 'print(full_message)'
In [6]: _ii # Second to last inputOut[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 indexOut[9]: 'name = "IPython"'Note: In[0] or _ih[0] usually holds an empty string or session startup information.
Output Caching
Section titled “Output Caching”IPython also caches the results (outputs) of your commands:
Outdictionary: 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 cellnusing the shortcut_<n>(e.g.,_5retrieves the output ofOut[5])._ohdictionary: Similar toOut, this dictionary holds the output history.
In [1]: 10 * 2Out[1]: 20
In [2]: 3 + 5Out[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 outputOut[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 outputOut[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.