Batu Lab NotesPractical developer guides

Build a histogram from integer buckets

By Batu · English technical notes

Also published in our primary archive.

To build a histogram from integer buckets in Python, calculate each bin number with value // width and count those bin numbers. For [0, 1, 4, 5, 9] at width 5, that produces the histogram {0: 3, 1: 2}. The companion grouping is {0: [0, 1, 4], 1: [5, 9]}, which makes the bin memberships inspectable.

The failing expression uses rounding after shifting the quotient: round(value / width - 0.5). It incorrectly places the boundary value 5 in bucket 0. This is a useful contrast, but it does not define half-open integer intervals. Python documents // as floor division; for these non-negative values, dividing by 5 maps 0–4 to 0 and 5–9 to 1. Python also documents that round() rounds ties to the nearest even multiple, so it should not be used as a substitute for interval membership.

Counter turns the computed bucket numbers into histogram counts. The separate defaultdict(list) retains the source values per bucket, while the assertion verifies that the original list has not changed. This fixture only establishes the stated behavior for non-negative integers and positive width 5. For negative inputs, choose and document a bin convention: floor division maps -1 // 5 to -1.

This uses longstanding Python 3 standard-library APIs; no newer minimum version is required.

AI assistance disclosure: this article was prepared with AI assistance and checked against the shown synthetic fixture.

Sources: Python arithmetic operators, Python round(), and Python collections.Counter.

from collections import Counter, defaultdict

values = [0, 1, 4, 5, 9]
width = 5

rounded_members = defaultdict(list)
floor_members = defaultdict(list)
for value in values:
    rounded_members[round(value / width - 0.5)].append(value)
    floor_members[value // width].append(value)

histogram = Counter(value // width for value in values)

assert values == [0, 1, 4, 5, 9]
assert dict(rounded_members) == {0: [0, 1, 4, 5], 1: [9]}
assert dict(floor_members) == {0: [0, 1, 4], 1: [5, 9]}
assert dict(histogram) == {0: 3, 1: 2}

print("input:", values)
print("rounded boundary members:", dict(rounded_members))
print("floor-division members:", dict(floor_members))
print("histogram counts:", dict(histogram))
input: [0, 1, 4, 5, 9]
rounded boundary members: {0: [0, 1, 4, 5], 1: [9]}
floor-division members: {0: [0, 1, 4], 1: [5, 9]}
histogram counts: {0: 3, 1: 2}