Need to create a progress bar in Python?
If so, in this short guide, you’ll see how to create a progress bar in Python using the tqdm package. You’ll also see how to add the GUI below 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 syntax:
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 myList = ['aaa','bbb','ccc','ddd','eee'] for i in myList: time.sleep(2) print(i)
After about 10 seconds ( = 5 items * 2 seconds per item), all the items in the list will be printed:
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(myList)
So the complete Python code would look like this:
import time from tqdm import tqdm myList = ['aaa','bbb','ccc','ddd','eee'] for i in tqdm(myList): time.sleep(2) print(i)
You’ll now see the progress bar, which should take about 10 seconds to complete:
Step 4 (optional): Add a GUI to track your progress
Did you know that you can also include a GUI to display your progress bar visually?
You can certainly do so by changing the syntax in two places:
- from tqdm import tqdm_gui
- tqdm_gui(myList)
So the complete Python code would look like this:
import time from tqdm import tqdm_gui myList = ['aaa','bbb','ccc','ddd','eee'] for i in tqdm_gui(myList): time.sleep(2) print(i)
You’ll now see the GUI with the progress bar:
Note that when you run the code, you may get the warning of: TqdmExperimentalWarning: GUI is experimental/alpha.
Progress Bar with a List Comprehension
Optionally, you may also find it useful to add a progress bar when dealing with a list comprehension:
import time from tqdm import tqdm_gui myList = ['aaa','bbb','ccc','ddd','eee'] myList = [(time.sleep(2), print(i)) for i in tqdm_gui(myList)]
Run the code, and you’ll get the following GUI as before: