How to Use tqdm in Python for Progress Bars
Use
tqdm by wrapping your iterable with tqdm() to display a progress bar in the console. Import it with from tqdm import tqdm and then use it in loops like for item in tqdm(iterable): to track progress visually.Syntax
The basic syntax to use tqdm is to wrap your iterable with tqdm(). This shows a progress bar that updates as the loop runs.
from tqdm import tqdm: imports the progress bar function.tqdm(iterable): wraps the iterable to track progress.for item in tqdm(iterable):: loops through items showing progress.
python
from tqdm import tqdm for i in tqdm(range(100)): pass
Output
100%|██████████| 100/100 [00:00<00:00, 100000.00it/s]
Example
This example shows how to use tqdm to display a progress bar while processing a list of items with a delay to simulate work.
python
from tqdm import tqdm import time items = list(range(10)) for item in tqdm(items, desc='Processing items'): time.sleep(0.2) # Simulate work
Output
Processing items: 100%|██████████| 10/10 [00:02<00:00, 4.99it/s]
Common Pitfalls
Common mistakes when using tqdm include:
- Not importing
tqdmproperly. - Wrapping something that is not iterable.
- Using
tqdminside nested loops without managing multiple bars. - Not flushing output in some environments, causing the bar not to update.
Always ensure your iterable is valid and import tqdm correctly.
python
from tqdm import tqdm # Wrong: passing a non-iterable # for i in tqdm(100): # pass # Right: for i in tqdm(range(100)): pass
Output
100%|██████████| 100/100 [00:00<00:00, 100000.00it/s]
Quick Reference
| Feature | Usage Example | Description |
|---|---|---|
| Basic progress bar | for i in tqdm(range(50)): | Wraps iterable to show progress |
| Add description | tqdm(iterable, desc='Loading') | Shows a label before the bar |
| Set total manually | tqdm(total=100) | Useful for unknown iterable lengths |
| Disable bar | tqdm(iterable, disable=True) | Turns off progress display |
| Nested bars | tqdm(..., position=0), tqdm(..., position=1) | Show multiple bars in loops |
Key Takeaways
Import tqdm with 'from tqdm import tqdm' before use.
Wrap your iterable with tqdm() to get a progress bar in loops.
Use the 'desc' parameter to add a label to the progress bar.
Avoid passing non-iterables to tqdm to prevent errors.
For nested loops, manage multiple bars with the 'position' argument.