When we work with Jupyter Notebook, it is often possible to run a computationally expensive command without storing it in a variable, where we may want to use it later. The good news is that we do not have to re-run the command since Jupyter stores all the outputs. The following example clarifies the above statement. Let’s assume that we open a Jupyter Notebook and we run a simple command such as:
5+5
Now, let’s say that we want to use the output of the previous cell and add the number 5 to it. We can easily do it by calling the value that we get on the left of the output cell, which is in the form Out[x]
where x
is an integer. Let’s have a look at the screenshot below.
As we can see, the Out[1]
is equal to 10
and the Out[2]
is equal to 15
. Notice that Jupyter stores all the outputs in a dictionary called Out
. We can confirm it by running:
type(Out)
dict
And the keys of the dictionary are the commands that we have run, starting with 1,2,3,…,n. For example, in our case we have run 4 commands so far, and we have the following keys:
Out.keys()
dict_keys([1, 2, 3, 4])
Finally, we can iterate over the output commands by running a for loop such as:
for k,v in Out.items(): print(k,v)
1 10
2 15
3 15
4 <class 'dict'>
5 dict_keys([1, 2, 3, 4, 5])
Last but not least, the Jupyter notebook stores all the commands that we have run too in a list
data type called In
. For example, in our case:
In
['',
'5+5',
'5+Out[1]',
'Out[2]',
'type(Out)',
'Out.keys()',
'for k,v in Out.items():\n print(k,v)',
'In']