How to display a progress bar in Jupyter Notebook

Usually, when we run long computations we include some print statements like this one:

1
2
3
4
5
6
7
8
number_of_elements = 1000

for i in range(number_of_elements):
    if i % 100 == 0:
        print(i)
    time.sleep(0.01) #Here should be the code that does the computation.

print('Done')

We end up with something similar to this output:

We do it because we wonder whether the Notebook is still running. We want to see the progress. That is sufficient, but it does not look good, does it?

What if we could display a progress bar? We can! Here is the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import time, sys
from IPython.display import clear_output

def update_progress(progress):
    bar_length = 20
    if isinstance(progress, int):
        progress = float(progress)
    if not isinstance(progress, float):
        progress = 0
    if progress < 0:
        progress = 0
    if progress >= 1:
        progress = 1

    block = int(round(bar_length * progress))
    clear_output(wait = True)
    text = "Progress: [{0}] {1:.1f}%".format( "#" * block + "-" * (bar_length - block), progress * 100)
    print(text)

And now, when we run the computation we see a nice progress bar ;)

1
2
3
4
5
6
7
number_of_elements = 1000

for i in range(number_of_elements):
    time.sleep(0.1) #Replace this with a real computation
    update_progress(i / number_of_elements)

update_progress(1)

The solution is based on Philip Osborne’s blog post and an answer to the StackOverflow question.

Did you enjoy reading this article?
Would you like to learn more about leveraging AI to drive growth and innovation, software craft in data engineering, and MLOps?

Subscribe to the newsletter or add this blog to your RSS reader (does anyone still use them?) to get a notification when I publish a new essay!

Newsletter

Do you enjoy reading my articles?
Subscribe to the newsletter if you don't want to miss the new content, business offers, and free training materials.

Bartosz Mikulski

Bartosz Mikulski

  • MLOps engineer by day
  • AI and data engineering consultant by night
  • Python and data engineering trainer
  • Conference speaker
  • Contributed a chapter to the book "97 Things Every Data Engineer Should Know"
  • Twitter: @mikulskibartosz
  • Mastodon: @mikulskibartosz@mathstodon.xyz
Newsletter

Do you enjoy reading my articles?
Subscribe to the newsletter if you don't want to miss the new content, business offers, and free training materials.