Using tqdm( ) for progress bars in python

tqdm gives a console kind of progress bar for our processes. Using tqdm is a straightforward process explained in the following steps:

1. Install the Requirements

First, we need to install our required library tqdm. Open a New Jupyter Notebook and execute:

!pip install tqdm !pip install time

This will complete the installation of tqdm. Restart the Kernel to start using the tqdm.

2. Import the Libraries

Import the newly installed tqdm and time library

from tqdm import tqdm import time

3. Using tqdm()

Now we will use the function tqdm() on a simple program with a for loop .

for i in tq(range(20)): time.sleep(0.5)

Here i is the variable that takes a value of the number 0 to 19 during each iteration. During each iteration, the system will sleep for 0.5 seconds before moving to the next iteration.

The complete code would look like this:

from tqdm import tqdm import time for i in tq(range(20)): time.sleep(0.5)

On Completion of Code Execution, we get:

Image Source – Personal Computer

We can also give attributes to tqdm() such as desc, which takes a string and will get added as a prefix before the progress bar. Thus,

from tqdm import tqdm import time for i in tqdm(range(20), desc = ‘tqdm() Progress Bar’): time.sleep(0.5)

On Completion of Code Execution, we get:

Image Source – Personal Computer

Apart from the progress bar, tqdm gives additional information such as the number of iterations completed out of the total number of iterations, Total Elapsed Time, Estimated Time to Complete the whole loop, and the speed of the loop in iterations per second (or it/s).