Search code examples
python-3.xtqdm

How to create one processing bar with triple loop?


I have a code likes

from tqdm import tqdm import time

for i in tqdm(range(10)):
    for j in tqdm(range(20)):
        for k in tqdm(range(30)):
            time.sleep(0.01)

It will create three processing bars as

10%|████▍                                       | 1/10 [00:06<00:54,  6.06s/it
50%|█████████████████████▌                     | 10/20 [00:03<00:03,  3.30it/s]
50%|█████████████████████▌                     | 15/30 [00:03<00:03,  3.30it/s]

Because the total number of iteration will be 10x20x30=6000. How can we make a single processing bar, but still using triple loop using python 3? The result likes

50%|█████████████████████▌                     | 3000/6000 [00:03<00:03,  3.30it/s]

Solution

  • You can un-attach tqdm from your loops like this:

    with tqdm(total=6000) as t:
    
        for i in range(10):
            for j in range(20):
                for k in range(30):
                    time.sleep(0.01)
                    t.update()
    

    Then whatever else you're doing inside your loops happens as expected, and the single progress bar to 6000 only updates during each iteration of the inner-most loop.