IntervalTree

3.2.1 · active · verified Fri Apr 17

IntervalTree is an editable, robust, and fast interval tree data structure for Python 2 and 3. It efficiently stores collections of intervals and allows for quick querying of overlapping or encompassing intervals. The current version is 3.2.1, with releases typically occurring a few times a year, focusing on bug fixes, performance improvements, and Python version compatibility.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create an IntervalTree, add intervals using both slice notation and explicit `Interval` objects, and perform common queries like finding intervals at a point, overlapping a range, or enveloping another range. It also shows how to remove an interval.

from intervaltree import Interval, IntervalTree

# Create an empty interval tree
tree = IntervalTree()

# Add intervals. You can assign data or just add the interval.
# Using slice notation for convenience (requires data assignment)
tree[0:10] = "first_interval"
tree[5:15] = "second_interval"

# Or add Interval objects explicitly
tree.add(Interval(12, 18, "third_interval"))

print(f"Tree size: {len(tree)}")

# Querying intervals
# Find all intervals overlapping a point
intervals_at_point = tree[7] # Using slice notation for point query
print(f"Intervals at point 7: {intervals_at_point}")

# Find all intervals overlapping a range
overlapping_intervals = tree.overlap(6, 13)
print(f"Intervals overlapping [6, 13): {overlapping_intervals}")

# Find all intervals that fully envelop another interval
enveloping_intervals = tree.envelop(4, 8)
print(f"Intervals enveloping [4, 8): {enveloping_intervals}")

# Remove an interval
interval_to_remove = Interval(0, 10, "first_interval")
tree.remove(interval_to_remove)
print(f"Tree size after removal: {len(tree)}")

view raw JSON →