tqdm

A fast, extensible progress bar for Python and CLI. Instantly makes your loops show a smart progress meter with ETA, iterations per second, and customizable statistics. Minimal overhead. Use for monitoring long-running loops, simulations, data processing, ML training, file downloads, I/O operations, command-line tools, pandas operations, parallel tasks, and nested progress bars.

9 stars

Best use case

tqdm is best used when you need a repeatable AI agent workflow instead of a one-off prompt.

A fast, extensible progress bar for Python and CLI. Instantly makes your loops show a smart progress meter with ETA, iterations per second, and customizable statistics. Minimal overhead. Use for monitoring long-running loops, simulations, data processing, ML training, file downloads, I/O operations, command-line tools, pandas operations, parallel tasks, and nested progress bars.

Teams using tqdm should expect a more consistent output, faster repeated execution, less prompt rewriting.

When to use this skill

  • You want a reusable workflow that can be run more than once with consistent structure.

When not to use this skill

  • You only need a quick one-off answer and do not need a reusable workflow.
  • You cannot install or maintain the underlying files, dependencies, or repository context.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/tqdm/SKILL.md --create-dirs "https://raw.githubusercontent.com/tondevrel/scientific-agent-skills/main/skills/tqdm/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/tqdm/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How tqdm Compares

Feature / AgenttqdmStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/A

Frequently Asked Questions

What does this skill do?

A fast, extensible progress bar for Python and CLI. Instantly makes your loops show a smart progress meter with ETA, iterations per second, and customizable statistics. Minimal overhead. Use for monitoring long-running loops, simulations, data processing, ML training, file downloads, I/O operations, command-line tools, pandas operations, parallel tasks, and nested progress bars.

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

SKILL.md Source

# tqdm - Intelligent Progress Bars

tqdm is the standard tool for monitoring long-running loops in Python. It has negligible overhead (about 60ns per iteration) and works everywhere: in the console, in Jupyter notebooks, and even in GUIs.

## When to Use

- Monitoring long-running loops (simulations, data processing, ML training).
- Tracking progress of file downloads or I/O operations.
- Providing visual feedback in command-line tools.
- Integrating progress tracking into pandas operations (progress_apply).
- Monitoring parallel tasks in concurrent.futures or multiprocessing.
- Creating nested progress bars for hierarchical tasks (e.g., epochs and batches).

## Reference Documentation

**Official docs**: https://tqdm.github.io/  
**GitHub**: https://github.com/tqdm/tqdm  
**Search patterns**: `from tqdm import tqdm`, `tqdm.pandas()`, `tqdm.notebook`, `tqdm.contrib`

## Core Principles

### Iterative Wrapper
The simplest way to use tqdm is to wrap any iterable: `for item in tqdm(iterable):`. It automatically calculates the length and estimates the time remaining.

### Low Overhead
tqdm is written to be extremely fast. It uses smart algorithms to limit the number of display updates so it doesn't slow down your actual computation.

### Integration
tqdm has specialized modules for different environments (Jupyter, Keras, Pandas, Slack/Telegram notifications).

## Quick Reference

### Installation

```bash
pip install tqdm
```

### Standard Imports

```python
from tqdm import tqdm
import time

# For Jupyter Notebooks specifically:
# from tqdm.notebook import tqdm
```

### Basic Pattern - Automatic Loop Tracking

```python
import time
from tqdm import tqdm

# Just wrap the range or list
for i in tqdm(range(1000)):
    time.sleep(0.01) # Simulate work
```

## Critical Rules

### ✅ DO

- **Use desc** - Add a description to the bar so you know exactly which process is running (`tqdm(range(10), desc="Processing")`).
- **Use leave=False for nested loops** - This cleans up the inner bars after they finish, preventing console clutter.
- **Use the notebook version** - In Jupyter, use `from tqdm.notebook import tqdm` for pretty HTML bars.
- **Set total manually** - If your iterator doesn't have a `__len__`, provide the `total` parameter manually.
- **Integrate with Pandas** - Use `tqdm.pandas()` to see progress on `.progress_apply()`.
- **Close manual bars** - If using the manual `pbar = tqdm(...)` approach, always use a `with` statement or call `pbar.close()`.

### ❌ DON'T

- **Update too often** - Avoid manual updates in tight loops (e.g., millions of updates per second); tqdm handles this automatically if you wrap the iterator.
- **Print to console inside tqdm** - Standard `print()` will break the bar. Use `tqdm.write("message")` instead.
- **Ignore overhead** - While low, if your loop body is sub-microsecond, any overhead matters; process in batches instead.
- **Forget ascii=True** - If working on old terminals or Windows CMD without Unicode support, use `ascii=True` to avoid garbled characters.

## Anti-Patterns (NEVER)

```python
from tqdm import tqdm
import time

# ❌ BAD: Mixing print() and tqdm (Corrupts the bar)
for i in tqdm(range(5)):
    print(f"Doing step {i}") # Bar jumps to next line
    time.sleep(0.1)

# ✅ GOOD: Use tqdm.write()
for i in tqdm(range(5)):
    tqdm.write(f"Doing step {i}") # Bar stays at the bottom
    time.sleep(0.1)

# ❌ BAD: Manual update without closing (Potential memory leak/UI hang)
pbar = tqdm(total=100)
for i in range(100):
    pbar.update(1)
# Missing pbar.close()!

# ✅ GOOD: Use context manager
with tqdm(total=100) as pbar:
    for i in range(100):
        pbar.update(1)

# ❌ BAD: Wrapping an iterator with no length without 'total'
# tqdm(my_generator) # Shows count but no progress bar/ETA
```

## Advanced Usage and Customization

### Descriptions and Statistics

```python
pbar = tqdm(range(100))
for i in pbar:
    # Update description dynamically
    pbar.set_description(f"Processing Step {i}")
    
    # Add custom stats (e.g., loss in ML)
    pbar.set_postfix(loss=0.5/(i+1), accuracy=i/100)
    time.sleep(0.05)
```

### Manual Control (For Non-Iterative Work)

```python
# Useful for tracking bytes in file I/O or API calls
with tqdm(total=1024, unit='B', unit_scale=True, desc="Downloading") as pbar:
    # Simulate chunked download
    for chunk_size in [256, 128, 512, 128]:
        time.sleep(0.5)
        pbar.update(chunk_size)
```

## Integration with Ecosystems

### Pandas Integration

```python
import pandas as pd
from tqdm import tqdm

# Initialize tqdm for pandas
tqdm.pandas(desc="Cleaning Data")

df = pd.DataFrame({'val': range(10000)})

# Use progress_apply instead of apply
result = df['val'].progress_apply(lambda x: x**2)
```

### Nested Progress Bars

```python
# Perfect for Epochs vs Batches in deep learning
for epoch in tqdm(range(3), desc="Epochs"):
    for batch in tqdm(range(10), desc="Batches", leave=False):
        time.sleep(0.05)
```

### Parallel Processing (concurrent.futures)

```python
from concurrent.futures import ThreadPoolExecutor
from tqdm import tqdm

def work(n):
    time.sleep(0.1)
    return n * 2

data = range(50)
with ThreadPoolExecutor() as executor:
    # Use tqdm to monitor map results
    results = list(tqdm(executor.map(work, data), total=len(data)))
```

## Practical Workflows

### 1. Large File Reader with Progress

```python
import os

def read_large_file(filepath):
    """Read a file while showing a progress bar based on bytes."""
    file_size = os.path.getsize(filepath)
    with tqdm(total=file_size, unit='B', unit_scale=True, unit_divisor=1024) as pbar:
        with open(filepath, 'rb') as f:
            for chunk in iter(lambda: f.read(4096), b''):
                # Process chunk
                pbar.update(len(chunk))
```

### 2. Scientific Simulation Suite

```python
def run_simulation_suite(configs):
    """Run multiple simulations and log failures."""
    results = []
    with tqdm(configs, desc="Suite") as pbar:
        for config in pbar:
            try:
                res = run_single_sim(config)
                results.append(res)
            except Exception as e:
                tqdm.write(f"Error in config {config}: {e}")
            pbar.set_postfix(success=len(results))
    return results
```

### 3. Training Loop with Custom Postfix

```python
def train_model(epochs, data_loader):
    pbar = tqdm(range(epochs), desc="Training")
    for epoch in pbar:
        loss = compute_loss() # dummy
        acc = compute_acc()   # dummy
        
        # Update the bar with current metrics
        pbar.set_postfix(loss=f"{loss:.4f}", acc=f"{acc:.2%}")
```

## Performance Optimization

### The mininterval parameter

By default, tqdm updates every 0.1 seconds. If your terminal is slow (e.g., over SSH or a legacy GUI), increase `mininterval` to 1.0 or 5.0 to reduce network/I/O traffic.

```python
for i in tqdm(range(1000000), mininterval=1.0):
    pass
```

### Disabling tqdm in Production

You can globally disable bars (e.g., when running in a CI/CD environment or a non-interactive log) by setting `disable=True`.

```python
import os
# Check for environment variable
is_ci = os.environ.get('CI') == 'true'
for i in tqdm(range(100), disable=is_ci):
    pass
```

## Common Pitfalls and Solutions

### The "Double Bar" Glitch

In Jupyter, sometimes bars don't close properly, leading to stacks of red/green bars.

```python
# ✅ Solution: Always use a 'with' statement or try-finally
# Or clear all instances if stuck:
from tqdm import tqdm
tqdm._instances.clear()
```

### Unicode Error on Windows

Windows CMD (non-Terminal) often struggles with the smooth progress blocks.

```python
# ✅ Solution: Use ASCII characters only
for i in tqdm(range(100), ascii=True):
    pass
```

### Multiple Bars Alignment

If your bars are overlapping or jumping:

```python
# ✅ Solution: Specify the position explicitly
# Useful for manual multi-threading
pbar1 = tqdm(total=100, position=0)
pbar2 = tqdm(total=100, position=1)
```

tqdm is a small addition to a script that provides immense psychological relief. It provides the "pulse" of your code, ensuring you are always aware of how your long-running scientific tasks are progressing.

Related Skills

xgboost-lightgbm

9
from tondevrel/scientific-agent-skills

Industry-standard gradient boosting libraries for tabular data and structured datasets. XGBoost and LightGBM excel at classification and regression tasks on tables, CSVs, and databases. Use when working with tabular machine learning, gradient boosting trees, Kaggle competitions, feature importance analysis, hyperparameter tuning, or when you need state-of-the-art performance on structured data.

xarray

9
from tondevrel/scientific-agent-skills

N-dimensional labeled arrays and datasets in Python. Built on top of NumPy and Dask. It introduces labels in the form of dimensions, coordinates, and attributes on top of raw NumPy-like arrays, making data analysis in physical sciences more intuitive and less error-prone. Use for working with multi-dimensional scientific data, NetCDF/GRIB/Zarr files, climate/weather/oceanographic datasets, remote sensing, geospatial imaging, large out-of-memory datasets with Dask, and labeled array operations.

transformers

9
from tondevrel/scientific-agent-skills

State-of-the-art Machine Learning for PyTorch, TensorFlow, and JAX. Provides thousands of pretrained models to perform tasks on different modalities such as text, vision, and audio. The industry standard for Large Language Models (LLMs) and foundation models in science.

tensorflow

9
from tondevrel/scientific-agent-skills

Comprehensive deep learning framework for building, training, and deploying neural networks. TensorFlow provides tf.keras high-level API for model construction, tf.data for efficient data pipelines, and tf.function for graph-mode optimization. Use when working with: neural network training and inference, image classification/detection/segmentation, NLP/text processing with embeddings or transformers, time series forecasting, generative models (VAE, GAN), transfer learning with pretrained models, custom training loops with GradientTape, GPU/TPU accelerated computation, or any deep learning task.

sympy

9
from tondevrel/scientific-agent-skills

Comprehensive guide for SymPy - Python library for symbolic mathematics. Use for symbolic expressions, calculus (derivatives, integrals, limits, series), equation solving (algebraic, differential, systems), linear algebra, simplification, matrix operations, special functions, code generation, and mathematical proofs. Essential for analytical mathematics and computer algebra.

sunpy

9
from tondevrel/scientific-agent-skills

The community-developed free and open-source software package for solar physics. Provides tools for data search and download, coordinate transformations specific to solar physics, and powerful image processing through the Map object. Use when working with solar data, solar images (EUV, magnetograms, white light), solar coordinates (Helioprojective, Heliographic), Fido data search, solar time series, differential rotation, limb fitting, or multi-instrument solar analysis (AIA, HMI, GOES).

statsmodels

9
from tondevrel/scientific-agent-skills

Advanced statistical modeling and hypothesis testing. Complementary to SciPy's stats module, it provides classes and functions for the estimation of many different statistical models, as well as for conducting statistical tests and statistical data exploration. Use for linear regression, GLM, time series analysis, ANOVA, survival analysis, causal inference, and statistical hypothesis testing. Load when working with OLS, WLS, logistic regression, Poisson regression, ARIMA, SARIMAX, statistical diagnostics, p-values, confidence intervals, or R-style statistical analysis.

spacy-nltk

9
from tondevrel/scientific-agent-skills

Natural Language Processing for text analysis, corpus linguistics, and production NLP pipelines. spaCy provides fast production-grade tokenization, POS tagging, NER, dependency parsing, and custom model training. NLTK provides classical corpus linguistics, linguistic analysis, VADER sentiment, collocation analysis, and access to standard linguistic corpora. Use when: processing and analyzing text data, extracting named entities (people, orgs, locations, dates), dependency parsing and syntactic analysis, building text classification pipelines, performing corpus-level linguistic analysis (frequency, collocations, readability), sentiment analysis, lemmatization and stemming, working with multilingual text, training custom NER or text classifiers, or any task requiring structured understanding of natural language beyond simple string operations.

sktime-tsfresh

9
from tondevrel/scientific-agent-skills

Time series machine learning layer (Tier 1): integration of **sktime** and **tsfresh** for building production-grade pipelines that transform raw time series into tabular feature representations suitable for classical machine-learning models. *sktime* provides a unified, sklearn-compatible interface for time-series data types, transformations, and pipelines, while *tsfresh* enables large-scale automated extraction of statistical, spectral, and autocorrelation features, with optional statistically grounded feature relevance selection (FRESH).

sklearn-explainability

9
from tondevrel/scientific-agent-skills

Advanced sub-skill for scikit-learn focused on model interpretability, feature importance, and diagnostic tools. Covers global and local explanations using built-in inspection tools and SHAP/LIME integrations.

sklearn-advanced

9
from tondevrel/scientific-agent-skills

Professional sub-skill for scikit-learn focused on robust pipeline architecture, custom estimator development, advanced feature engineering, and rigorous model validation. Covers Target Encoding, Nested Cross-Validation, and Production Deployment.

simpy

9
from tondevrel/scientific-agent-skills

A process-based discrete-event simulation framework. Use for modeling queuing systems, supply chains, manufacturing processes, network simulation, project management, and any system where events occur at specific points in time. Load when working with discrete event simulation, process modeling, resource allocation, virtual time, simpy.Environment, simpy.Resource, or event-driven simulation.