12

Here is an example for nested tqdm bar

import time
import tqdm
for i in tqdm.tqdm(range(3)):
    for j in tqdm.tqdm(range(5)):
        print(i," : ", j)

I try it on jupyter notebook but it does not show any thing without error! However, it works coorectly on ipython console!

Jeanne
  • 1,241
  • 3
  • 19
  • 28
  • 1
    I came here to post the same question. I have problems with this exact scenario, although my manifestation of the problem is different. Instead of an updating bar, I instead get a new bar printed for every update. So in the code example posted, I would actually have ~15 bars printed right after one another (actually, I think a few more since we get one at a 0 status as well). CORRECTION: I'd get 3 bars since the inner loop is fast enough. Add in a time.sleep(1.5) in the inner loop and then you get the ~15 bars. – Jaxidian Aug 03 '18 at 14:36
  • TL;DR: nesting "just works", but in jupyter you need to `from tqdm.notebook import tqdm`. – Tomasz Gandor Nov 29 '19 at 18:08

1 Answers1

14

I just found the solution that I'm going to use. The solution has plenty of examples here.

I've modified the example in the original post with both the solution as well as a time delay for visualization purposes (the final output is the same with or without the delay).

from time import sleep
from tqdm import tqdm_notebook
for i in tqdm_notebook(range(3)):
    for j in tqdm_notebook(range(5)):
        sleep(0.1)
        print(i," : ", j)

print("Done!")

The final output looks like this. While it's processing, it's pleasant to watch at (no jumping around or anything crazy).

Image of the final output after completion


One little hack that I'm now doing to make this a super easy drop-in replacement is to pull in tqdm like this, so I don't have to change any other code:

from time import sleep
from tqdm import tqdm_notebook as tqdm
for i in tqdm(range(3)):
    for j in tqdm(range(5)):
        sleep(0.1)
        print(i," : ", j)

print("Done!")
Jaxidian
  • 13,081
  • 8
  • 83
  • 125