Search code examples
pythontqdm

print tqdm internal counter value


How to print tqdm internal counter value? Need this to avoid using extra enumerate wrapper. Somehow .n attribute is not working

# my example:
from tqdm.auto import tqdm
s = 'abcd'
pb = tqdm(s)
for character in pb:
    print(pb.n, end = ' ')

output   >>> 0 0 0 0
expected >>> 0 1 2 3

Solution

  • For performance reasons, tqdm doesn't update the n parameter immediately, but only after both a certain number of iterations and a certain time have elapsed (relevant source code here). The empty loop is too quick to allow the time condition to be true on a modern computer.

    You can adjust these waiting intervals by setting miniters and mininterval to force pb.n to be updated every loop:

    rec = []
    s = "abcd"
    pb = tqdm(s, miniters=1, mininterval=0)
    for character in pb:
        print(pb.n, end=" ")