Red-Black Tree Implementation in Python
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Red-Black Tree runs in O(log n) time and O(n) space, in Python as in every other language.
- ✓None. Python has no ordered mapping in the standard library at all: dict is a hash that happens to preserve insertion order since 3.7, which is not key order, and there is no tree anywhere.
- ✓Do not write one. Use a sorted list with the bisect module, or the third-party sortedcontainers package, which is the community standard and pointedly does not use a tree either.
- ✓The Python trap: A pure-Python red-black tree is a teaching exercise that loses to bisect on essentially every real input, and by a wide margin, because the rotations and recolourings are interpreted bytecode while the list insertion is a single memmove in C.
- ✓Every node is a Python object with a header and attribute storage, so the tree allocates n objects and chases n pointers, both of which are far more expensive than the equivalent C-level work inside a list operation.
What Red-Black Tree actually is
Red-Black Tree in Python: what you actually reach for
Python implementation
# Python has NO ordered mapping in the standard library. This is what
# the tree would be for, done the way that actually wins.
import bisect
class SortedIndex:
__slots__ = ("_keys", "_vals")
def __init__(self):
self._keys: list = []
self._vals: list = []
def __setitem__(self, key, value) -> None:
i = bisect.bisect_left(self._keys, key)
if i < len(self._keys) and self._keys[i] == key:
self._vals[i] = value
return
self._keys.insert(i, key) # O(n) memmove in C, still faster
self._vals.insert(i, value) # than interpreted rotations
def __getitem__(self, key):
i = bisect.bisect_left(self._keys, key)
if i < len(self._keys) and self._keys[i] == key:
return self._vals[i]
raise KeyError(key)
def range(self, lo, hi):
"""Ordered range scan, the operation a dict cannot do at all."""
start = bisect.bisect_left(self._keys, lo)
end = bisect.bisect_right(self._keys, hi)
return list(zip(self._keys[start:end], self._vals[start:end]))
def floor(self, key):
"""Largest key <= the argument."""
i = bisect.bisect_right(self._keys, key)
return self._keys[i - 1] if i else NoneThink Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Python-specific trap
Performance in Python, beyond the O(log n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Python type or library should I use for Red-Black Tree?
None. Python has no ordered mapping in the standard library at all: dict is a hash that happens to preserve insertion order since 3.7, which is not key order, and there is no tree anywhere.
What is the most common Python mistake when implementing Red-Black Tree?
A pure-Python red-black tree is a teaching exercise that loses to bisect on essentially every real input, and by a wide margin, because the rotations and recolourings are interpreted bytecode while the list insertion is a single memmove in C. The asymptotics say the tree should win above some size; the constant factors put that crossover far beyond where anyone actually operates. If you are writing one to use rather than to learn, measure the alternative first, because the measurement usually ends the project.
How does Red-Black Tree actually perform in Python?
Every node is a Python object with a header and attribute storage, so the tree allocates n objects and chases n pointers, both of which are far more expensive than the equivalent C-level work inside a list operation. Time complexity is O(log n) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialStudying for this? Student discounts on developer tools are collected on Noizz, tool by tool.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.