Loop construct is one of the most valuable and essential instructions in programming. Loops allow us to perform repetitive tasks in minimum lines of code.
It can be challenging to work on large datasets as we sometimes need to iterate over the whole; it seems to be stuck on the console screen. We can visualize the completion of the loop on the console screen with the progress bar. We can do so by using an external python package named tqdm
.
The word tqdm is a short form of the Arabic word 'taqaddum,' which means 'progress.' It helps us in visualizing the completion of the loop. It can be used in a nested loop.
Its overhead on the performance or speed is negligible. According to its official documentation, it is 60ns per iteration on the console screen, which is lower than any other visualizer.
In Python, the tqdm
library/package isn't pre-installed. We need to install it using the following pip command:
pip install tqdm
After installation, we can import and use its method in the loop.
We can visualize the loop's progress using the tqdm
package.
We can pass the list, and it automatically iterates over it.
We can provide the range to tqdm
.
tqdm()
methodThe tqdm()
method wraps around the iterable list of the loop and automatically detects and makes the progress bar on the console.
The following code will demonstrate the console's progress bar using a loop with ten iterations.
import tqdm import time list1=[2,3,5,7,11,13,17,19,23,29] for i in tqdm.tqdm(list1): time.sleep(1) print("The end")
Lines 1–2: We import tqdm and time libraries in the python script.
Line 3: We declare a list of integers of named list1
.
Line 4: We declare a loop and wrap the list in thetqdm.tqdm()
method.
Line 5: We call the sleep
method of time library that suspends the execution for
Line 7: We print ‘The end’
on the console when the loop finishes.
trange()
methodIt is the same as the range
keyword of python and can be used to iterate a loop to a specific range. But trange()
performs the same task and provides a progress bar visualizer on the output screen.
The following code snippet will show the working of the trange()
method.
import tqdm import time for i in tqdm.trange(1000): time.sleep(0.01) print("The end")
Lines 1–2: We are importing tqdm and time libraries in the python script.
Line 3: We declare a loop and give the range in the tqdm.trange()
method.
Line 4: We call the sleep
method of the time library that suspends the execution for 0.01 seconds.
Line 6: We print ‘The end’
on the console when the loop finishes
Free Resources