0
0
PythonHow-ToBeginner · 3 min read

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 tqdm properly.
  • Wrapping something that is not iterable.
  • Using tqdm inside 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

FeatureUsage ExampleDescription
Basic progress barfor i in tqdm(range(50)):Wraps iterable to show progress
Add descriptiontqdm(iterable, desc='Loading')Shows a label before the bar
Set total manuallytqdm(total=100)Useful for unknown iterable lengths
Disable bartqdm(iterable, disable=True)Turns off progress display
Nested barstqdm(..., 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.