Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an elegant, Pythonic way to count processed data? [duplicate]

I often have time consuming processing steps that occur within a loop. The following method is how I keep track of where the processing is at. Is there a more elegant, Pythonic way of counting processing data while a script is running?


n_items = [x for x in range(0,100)]

counter = 1
for r in n_items:
    # Perform some time consuming task...
    print "%s of %s items have been processed" % (counter, len(n_items))
    counter = counter + 1
like image 918
Borealis Avatar asked May 15 '26 17:05

Borealis


1 Answers

Yes, enumerate was built for this:

for i,r in enumerate(n_items,1):
    # Perform some time consuming task
    print('{} of {} items have been processed'.format(i, len(n_items)))

The second argument determines the starting value of i, which is 0 by default.