In this short guide, you’ll see how to create a progress bar in Python using the tqdm package. You’ll also observe how to add a GUI to track your progress.
Steps to Create a Progress Bar in Python
Step 1: Install the tqdm package
To begin, install the tqdm package using this command:
pip install tqdm
You may check the following guide for the instructions to install a package in Python using pip.
Step 2: Write the Python code
Let’s write a simple Python code to:
- Create a list with 5 items; and
- Apply 2 seconds delay before printing each item when iterating over the list
import time my_list = [1, 2, 3, 4, 5] for i in my_list: time.sleep(2) print(i)
After 10 seconds (5 items * 2 seconds per item), all the items in the list would be printed:
1
2
3
4
5
Step 3: Create the Progress Bar in Python
In order to create the progress bar in Python, simply add the highlighted syntax into the code:
- from tqdm import tqdm
- tqdm(my_list)
So the complete Python code would look like this:
from tqdm import tqdm import time my_list = [1, 2, 3, 4, 5] for i in tqdm(my_list): time.sleep(2) print(i)
You’ll now see the progress bar, which should take 10 seconds to complete.
Step 4 (optional): Add a GUI to track your progress
You may also include a GUI to display your progress bar visually.
You’ll need to change the syntax in two places:
- from tqdm import tqdm_gui
- tqdm_gui(my_list)
So the complete Python code would look like this:
from tqdm import tqdm_gui import time my_list = [1, 2, 3, 4, 5] for i in tqdm_gui(my_list): time.sleep(2) print(i)
You’ll now see the GUI with the progress bar.
Progress Bar with a List Comprehension
Optionally, you may also find it useful to add a progress bar when dealing with a list comprehension:
from tqdm import tqdm_gui import time my_list = [1, 2, 3, 4, 5] progress_bar = [(time.sleep(2), print(i)) for i in tqdm_gui(my_list)]
Run the code, and you’ll get the same GUI as before.