Skip to content

IPython - History Command

IPython meticulously records the commands you enter during a session. This history is easily accessible, making it simple to recall, modify, and re-execute previous commands.

The most direct way to access previous commands is using the Up and Down arrow keys in the IPython console or a Jupyter cell. Pressing Up scrolls backward through your command history, while Down scrolls forward.

For a more structured view of your command history, use the %history magic command. By default, it lists the commands entered in the current session.

In [1]: message = "Hello IPython"
In [2]: print(message)
# Output: Hello IPython
In [3]: %history
# Output:
# message = "Hello IPython"
# print(message)
# %history

You can control the output of %history with various options:

  • %history -n: Show history with line numbers.
  • %history 1-5: Show history from line 1 to 5.
  • %history ~1/1-5: Show history from line 1 to 5 of the previous session.
  • %history -g <pattern>: Search history for lines containing <pattern>.
In [4]: %history -n 1-2
# Output:
# 1: message = "Hello IPython"
# 2: print(message)

IPython also stores recent inputs and outputs in special variables, which are covered in detail in the ‘Input/Output Caching’ section. Briefly:

  • _, __, ___: Store the last three output values.
  • _i, _ii, _iii: Store the last three input strings.
  • In, _ih: Lists containing all input strings.
  • Out, _oh: Dictionaries mapping cell numbers to output values.

These features combined provide a powerful way to interact with and reuse your past computations.