Prerequisites and interval contract
A histogram can silently lose boundary observations when every bin excludes its upper edge. This Python 3.12 example uses bins that include their lower edge and exclude their upper edge, with one explicit exception: the final bin includes the last edge. It uses only bisect and math. No NumPy installation or plotting library is required.
The fixture uses edges zero, ten and twenty. The intervals are [0,10) and [10,20]. Values exactly equal to ten belong in the second bin, and twenty is retained in that same final bin. This convention is also documented by NumPy histogram, but the example implements and tests it directly rather than depending on that library.
Locate bins and retain excluded counts
bisect_right finds an insertion position after an equal edge. Subtracting one therefore selects the bin beginning at that edge. At the last edge, the insertion position would normally point beyond the last bin, so the code caps the accepted index at the final bin. The range check happens first; it prevents out-of-range values from being incorrectly squeezed into an end bin.
The input values are minus one, zero, nine, ten, nineteen, twenty and twenty-one. Two fall in the first bin, three in the second and two outside the range. The conservation assertion checks that bin counts plus outside count equals the number of observations. This makes dropped data visible even when the chart only displays the configured bins.
Validate observations and edges
Edges must be finite, numeric and strictly increasing. Duplicate edges would create zero-width intervals and are rejected. Reversed edges and an insufficient edge list are also invalid. Observations must be finite built-in numbers; NaN is rejected rather than being assigned to a bin through surprising comparison behavior. Booleans are excluded by the same exact-type policy. The math.isfinite checks require integers to be convertible to floating point; extremely large Python integers are outside this example's supported input range.
An empty observation list is valid and returns zero counts with no outside observations. Empty data and an invalid bin configuration are different conditions, so edge validation still occurs before scanning the data. The function accepts an iterable of observations, allowing a caller to process values without first retaining the entire input sequence.
Troubleshooting and reporting limits
If values appear in an adjacent bin unexpectedly, inspect how the upstream calculation represents them. Decimal-looking floating-point values can lie slightly above or below a displayed boundary. Do not add an arbitrary epsilon unless the measurement contract defines an appropriate tolerance. Integer units or decimal arithmetic may be better when business boundaries must be exact.
These are counts, not probability densities. With unequal-width bins, comparing bar heights as though they were densities can mislead. The example keeps explicit edges and raw counts so another layer can choose a justified presentation. The tests cover the final edge, interior edge, empty observations, invalid edge sets, NaN and conservation of all seven inputs. No automatic bin selection, weighted observations or plotting integration was tested.
Complete example
Save as histogram.py.
from bisect import bisect_right
from math import isfinite
def histogram(values, edges):
if len(edges) < 2 or any(type(x) not in (int, float) or not isfinite(x)
for x in edges):
raise ValueError("need finite bin edges")
if any(a >= b for a, b in zip(edges, edges[1:])):
raise ValueError("edges must strictly increase")
counts = [0] * (len(edges) - 1)
outside = 0
for x in values:
if type(x) not in (int, float) or not isfinite(x):
raise ValueError("invalid observation")
if x < edges[0] or x > edges[-1]:
outside += 1
continue
index = min(bisect_right(edges, x) - 1, len(counts) - 1)
counts[index] += 1
return counts, outside
values = [-1, 0, 9, 10, 19, 20, 21]
counts, outside = histogram(values, [0, 10, 20])
assert counts == [2, 3] and outside == 2
assert sum(counts) + outside == len(values)
assert histogram([], [0, 1]) == ([0], 0)
assert histogram([0, 10, 20], [0, 10, 20]) == ([1, 2], 0)
for edges in ([0], [0, 0], [1, 0], [0, float("inf")]):
try:
histogram([], edges)
except ValueError:
pass
else:
raise AssertionError("invalid edges accepted")
try:
histogram([float("nan")], [0, 1])
except ValueError:
pass
else:
raise AssertionError("NaN accepted")
print(f"counts={counts}; outside={outside}; accounted={sum(counts) + outside}")
Run and expected output
python3 histogram.pycounts=[2, 3]; outside=2; accounted=7Primary references
Continue with data-science tutorials.