IPython (Interactive Python) is an enhanced Python shell which provides a more robust and productive development environment for users. There are several key features that set it apart from the standard Python shell.


In IPython, all your inputs and outputs are saved. There are two variables named In and Out which are assigned as you work with your results. All outputs are saved automatically to variables of the form _N, where N is the prompt number, and inputs to _iN. This allows you to recover quickly the result of a prior computation by referring to its number even if you forgot to store it as a variable.

In [ ]:
import numpy as np
In [ ]:
In [ ]:
In [ ]:
_1 / 4.

Output is asynchronous

All output is displayed asynchronously as it is generated in the Kernel. If you execute the next cell, you will see the output one piece at a time, not all at the end.

In [ ]:
import time, sys
for i in range(8):


If you want details regarding the properties and functionality of any Python objects currently loaded into IPython, you can use the ? to reveal any details that are available:

In [ ]:
some_dict = {}

If available, additional detail is provided with two question marks, including the source code of the object itself.

In [ ]:
from numpy.linalg import cholesky

This syntax can also be used to search namespaces with wildcards (*).

In [ ]:
%matplotlib inline
import pylab as plt

Tab completion

Because IPython allows for introspection, it is able to afford the user the ability to tab-complete commands that have been partially typed. This is done by pressing the <tab> key at any point during the process of typing a command:

In [ ]:

This can even be used to help with specifying arguments to functions, which can sometimes be difficult to remember:

In [ ]:

System commands

In IPython, you can type ls to see your files or cd to change directories, just like you would at a regular system prompt:

In [ ]:
ls /Users/fonnescj/Teaching/Bios8366/data

Virtually any system command can be accessed by prepending !, which passes any subsequent command directly to the OS.

In [ ]:
!locate python | grep pdf

You can even use Python variables in commands sent to the OS:

In [ ]:
file_type = 'csv'
!ls ../data/*$file_type

The output of a system command using the exclamation point syntax can be assigned to a Python variable.

In [ ]:
data_files = !ls ../data/microbiome/
In [ ]:

Qt Console

If you type at the system prompt:

$ ipython qtconsole

instead of opening in a terminal, IPython will start a graphical console that at first sight appears just like a terminal, but which is in fact much more capable than a text-only terminal. This is a specialized terminal designed for interactive scientific work, and it supports full multi-line editing with color highlighting and graphical calltips for functions, it can keep multiple IPython sessions open simultaneously in tabs, and when scripts run it can display the figures inline directly in the work area.


Jupyter Notebook

Over time, the IPython project grew to include several components, including:

  • an interactive shell
  • a REPL protocol
  • a notebook document fromat
  • a notebook document conversion tool
  • a web-based notebook authoring tool
  • tools for building interactive UI (widgets)
  • interactive parallel Python

As each component has evolved, several had grown to the point that they warrented projects of their own. For example, pieces like the notebook and protocol are not even specific to Python. As the result, the IPython team created Project Jupyter, which is the new home of language-agnostic projects that began as part of IPython, such as the notebook in which you are reading this text.

The HTML notebook that is part of the Jupyter project supports interactive data visualization and easy high-performance parallel computing.

In [ ]:
import matplotlib.pyplot as plt

def f(x):
    return (x-3)*(x-5)*(x-7)+85

import numpy as np
x = np.linspace(0, 10, 200)
y = f(x)

The notebook lets you document your workflow using either HTML or Markdown.

The Jupyter Notebook consists of two related components:

  • A JSON based Notebook document format for recording and distributing Python code and rich text.
  • A web-based user interface for authoring and running notebook documents.

The Notebook can be used by starting the Notebook server with the command:

$ ipython notebook

This initiates an iPython engine, which is a Python instance that takes Python commands over a network connection.

The IPython controller provides an interface for working with a set of engines, to which one or more iPython clients can connect.

The Notebook gives you everything that a browser gives you. For example, you can embed images, videos, or entire websites.

In [ ]:
from IPython.display import HTML
HTML("<iframe src=http://fonnesbeck.github.io/Bios8366 width=700 height=350></iframe>")
In [ ]:
from IPython.display import YouTubeVideo

Remote Code

Use %load to add remote code

In [ ]:
%load http://matplotlib.org/mpl_examples/shapes_and_collections/scatter_demo.py

Mathjax Support

Mathjax ia a javascript implementation $\alpha$ of LaTeX that allows equations to be embedded into HTML. For example, this markup:

"""$$ \int_{a}^{b} f(x)\, dx \approx \frac{1}{2} \sum_{k=1}^{N} \left( x_{k} - x_{k-1} \right) \left( f(x_{k}) + f(x_{k-1}) \right). $$"""

becomes this:

$$ \int_{a}^{b} f(x)\, dx \approx \frac{1}{2} \sum_{k=1}^{N} \left( x_{k} - x_{k-1} \right) \left( f(x_{k}) + f(x_{k-1}) \right). $$

SymPy Support

SymPy is a Python library for symbolic mathematics. It supports:

  • polynomials
  • calculus
  • solving equations
  • discrete math
  • matrices
In [ ]:
from sympy import *
x, y = symbols("x y")
In [ ]:
eq = ((x+y)**2 * (x+1))
In [ ]:
In [ ]:
(1/cos(x)).series(x, 0, 6)
In [ ]:
limit((sin(x)-x)/x**3, x, 0)
In [ ]:
diff(cos(x**2)**2 / (1+x), x)

Magic functions

IPython has a set of predefined ‘magic functions’ that you can call with a command line style syntax. These include:

  • %run
  • %edit
  • %debug
  • %timeit
  • %paste
  • %load_ext
In [ ]:

Timing the execution of code; the timeit magic exists both in line and cell form:

In [ ]:
%timeit np.linalg.eigvals(np.random.rand(100,100))
In [ ]:
%%timeit a = np.random.rand(100, 100)

IPython also creates aliases for a few common interpreters, such as bash, ruby, perl, etc.

These are all equivalent to %%script <name>

In [ ]:
puts "Hello from Ruby #{RUBY_VERSION}"
In [ ]:
echo "hello from $BASH"

IPython has an rmagic extension that contains a some magic functions for working with R via rpy2. This extension can be loaded using the %load_ext magic as follows:

In [ ]:
%load_ext rpy2.ipython

If the above generates an error, it is likely that you do not have the rpy2 module installed. You can install this now via:

In [ ]:
!pip install rpy2
In [ ]:
x,y = np.arange(10), np.random.normal(size=10)
%R print(lm(rnorm(10)~rnorm(10)))
In [ ]:
%%R -i x,y -o XYcoef
lm.fit <- lm(y~x)
XYcoef <- coef(lm.fit)
In [ ]:


In addition to MathJax support, you may declare a LaTeX cell using the %latex magic:

In [ ]:
\nabla \times \vec{\mathbf{B}} -\, \frac1c\, \frac{\partial\vec{\mathbf{E}}}{\partial t} & = \frac{4\pi}{c}\vec{\mathbf{j}} \\
\nabla \cdot \vec{\mathbf{E}} & = 4 \pi \rho \\
\nabla \times \vec{\mathbf{E}}\, +\, \frac1c\, \frac{\partial\vec{\mathbf{B}}}{\partial t} & = \vec{\mathbf{0}} \\
\nabla \cdot \vec{\mathbf{B}} & = 0


Jupyter also enables objects to declare a JavaScript representation. At first, this may seem odd as output is inherently visual and JavaScript is a programming language. However, this opens the door for rich output that leverages the full power of JavaScript and associated libraries such as D3 for output.

In [ ]:

alert("Hello world!");

Exporting and Converting Notebooks

In Jupyter, one can convert an .ipynb notebook document file into various static formats via the nbconvert tool. Currently, nbconvert is a command line tool, run as a script using Jupyter.

In [ ]:
!jupyter nbconvert --to html Section0-IPython_and_Jupyter.ipynb

Currently, nbconvert supports HTML (default), LaTeX, Markdown, reStructuredText, Python and HTML5 slides for presentations. Some types can be post-processed, such as LaTeX to PDF (this requires Pandoc to be installed, however).

In [ ]:
!jupyter nbconvert --to pdf Section2_1-Introduction-to-Pandas.ipynb

A very useful online service is the IPython Notebook Viewer which allows you to display your notebook as a static HTML page, which is useful for sharing with others:

In [ ]:
<iframe src=http://nbviewer.ipython.org/2352771 width=700 height=300></iframe>

Also, GitHub supports the rendering of Jupyter Notebooks stored on its repositories.

Reproducible Research

reproducing conclusions from a single experiment based on the measurements from that experiment

The most basic form of reproducibility is a complete description of the data and associated analyses (including code!) so the results can be exactly reproduced by others.

Reproducing calculations can be onerous, even with one's own work!

Scientific data are becoming larger and more complex, making simple descriptions inadequate for reproducibility. As a result, most modern research is irreproducible without tremendous effort.

Reproducible research is not yet part of the culture of science in general, or scientific computing in particular.

Scientific Computing Workflow

There are a number of steps to scientific endeavors that involve computing:


Many of the standard tools impose barriers between one or more of these steps. This can make it difficult to iterate, reproduce work.

The Jupyter notebook eliminates or reduces these barriers to reproducibility.

Parallel iPython

At a high level, there are three basic components to parallel IPython:

  • Engine(s) - the remote or distributed processes where your code runs.
  • Client - your interface to running code on Engines.
  • Controller - the collection of processes that coordinate Engines and Clients.

These components live in the IPython.parallel package, which has been rolled out into its own model that requires installation.

To install ipyparallel:

pip install ipyparallel

or via conda:

conda install ipyparallel

To install the IPython Clusters tab in Jupyter Notebook, add this to your jupyter_notebook_config.py:


This file resides in your ~/.jupyter subdirectory of your home directory, and should be created if it does not already exist.

Before running the next cell, make sure you have first started your cluster, you can use the clusters tab in the dashboard to do so.

In [ ]:
from ipyparallel import Client
client = Client()
dv = client.direct_view()
In [ ]:
In [ ]:
def where_am_i():
    import os
    import socket
    return "In process with pid {0} on host: '{1}'".format(
        os.getpid(), socket.gethostname())
In [ ]:
where_am_i_direct_results = dv.apply(where_am_i)

IPython Notebook Viewer Displays static HTML versions of notebooks, and includes a gallery of notebook examples.

NotebookCloud A service that allows you to launch and control IPython Notebook servers on Amazon EC2 from your browser.

A Reference-Free Algorithm for Computational Normalization of Shotgun Sequencing Data A landmark example of reproducible research in genomics: Git repo, iPython notebook, data and scripts.

Jacques Ravel and K Eric Wommack. 2014. All Hail Reproducibility in Microbiome Research. Microbiome, 2:8.

Benjamin Ragan-Kelley et al.. 2013. Collaborative cloud-enabled tools allow rapid, reproducible biological insights. The ISME Journal, 7, 461–464; doi:10.1038/ismej.2012.123;