Bucket Numbers into Histogram Bin Counts in Python

Partition a list of numbers into equal-width histogram bins and count how many fall into each bin using only the Python standard library.

Easy Python 3.9+ Aug 9, 2026 Algorithms & data structures 17 views 0 copies

Python code

32 lines
Python 3.9+
from collections import Counter

def histogram_bins(numbers, num_bins):
    """Bucket numbers into histogram bin counts."""
    if not numbers:
        return []
    
    min_val = min(numbers)
    max_val = max(numbers)
    bin_width = (max_val - min_val) / num_bins
    
    # Handle edge case where all values are identical
    if bin_width == 0:
        return [len(numbers)] + [0] * (num_bins - 1)
    
    counts = [0] * num_bins
    for number in numbers:
        # Compute bin index, with max value going into the last bin
        index = min(int((number - min_val) / bin_width), num_bins - 1)
        counts[index] += 1
    
    return counts

if __name__ == "__main__":
    data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    bins = 5
    result = histogram_bins(data, bins)
    
    print(f"Data: {data}")
    print(f"Bins: {bins}")
    print(f"Counts: {result}")
    print(f"Sum of counts: {sum(result)} (should equal {len(data)})")

Output

stdout
Data: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Bins: 5
Counts: [2, 2, 2, 2, 2]
Sum of counts: 10 (should equal 10)

How it works

The function first computes the minimum and maximum of the data to establish the range, then divides that range by the number of bins to get a uniform bin width. For each number, it calculates an index by normalizing the number to its distance from the minimum and dividing by the bin width, then clamping to the last bin to handle the maximum value safely. A special case returns all counts in the first bin when all numbers are identical (bin width zero). The algorithm runs in O(n) time, making it efficient for large datasets.

Common mistakes

  • Forgetting to clamp the computed index to `num_bins - 1` so the maximum value lands in the last bin.
  • Not handling the case where all values are equal, which would cause division by zero.
  • Assuming the input is sorted when the algorithm works on unsorted data.

Variations

  1. Use `numpy.histogram` or `numpy.digitize` for faster bins on large arrays.
  2. Return bin edges alongside counts to build a full histogram representation.

Real-world use cases

  • Analyzing server response time distributions to create latency histograms for monitoring dashboards.
  • Grouping customer purchase amounts into price bands for marketing segmentation analysis.
  • Building image pixel intensity histograms for contrast adjustment in computer vision preprocessing.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Algorithms & data structures

Related tutorials and quizzes for this topic.