How to use tqdm to iterate over a list
Asked Answered
S

4

17

I would like to know how long it takes to process a certain list.

for a in tqdm(list1):
    if a in list2:
        #do something

but this doesnt work. If I use for a in tqdm(range(list1)) i wont be able to retrieve the list values.

Do you know how do do it?

Sunbreak answered 16/3, 2018 at 11:44 Comment(0)
A
32
import tqdm

for p in tqdm.tqdm([10,50]):
    print(p)

or

from tqdm import tqdm

for p in tqdm([10,50]):
    print(p)
Aldosterone answered 6/12, 2018 at 14:37 Comment(0)
T
8

I had also this problem. In my case I wrote:

import tqdm

instead

from tqdm import tqdm
Thad answered 9/4, 2019 at 13:53 Comment(0)
E
4

I've written so many answers because I personally have used all these at different places in my mini-projects and projects. Some may be irrelevant according to question, but will be useful elsewhere.

list1 = list(range(100))

import tqdm
for x in tqdm.tqdm(list1):
        sleep(0.01)

Or

tlist1 = tqdm.tqdm(list1)
for x in tlist1:
        sleep(0.01)

Basically, you are passing the list to create a tqdm instance.

You can use another workaround as in tqdm documentation:

# DOESN't work well in terminal, but should be ok in Jupyter Notebook
with tqdm.tqdm(total=len(list1)) as t:
    for x in list1:
        sleep(0.01)
        t.update(1)

Using generators with manual update of trange object:

def literate(list1):
    t = trange(len(list1))
    for x in list1:
        t.update(1)
        yield x

for x in literate(list1):
    sleep(0.01)

With automatic update:

def li_iterate(li):
    l = iter(li)
    for _ in trange(len(li)):
        yield next(l)

for x in li_iterate(list1):
    sleep(0.01)

Apart from the question, if you are using pandas dataframe, you may want to use this sometime (in google-colaboratory):

# %% implies cell magic in google-colab
%%capture
from tqdm.notebook import tqdm as tq
tq().pandas()

def fn(x):
    for a in list2:
        print(x, a)

import pandas as pd
list1 = list(range(0, 9))
pd.DataFrame(data=list1).progress_apply(fn)

-Himanshu

Esparto answered 10/12, 2020 at 12:4 Comment(0)
N
0

List is a list of elements in it, hence if you do len(ls), it gives you number of elements in the list. range builtin function will iterate over the range, hence following for loop should work for tqdm

from tqdm import tqdm

ls = [i for i in range(0,20000000)]

for i in tqdm(range(len(ls))):
  ## code goes here ##
  pass
Napoli answered 15/4, 2020 at 7:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.