Community Python Snippet

bisect Instead of sort() on Every Insert (Python)

I had a leaderboard insert loop running list.append + list.sort. Swapping to bisect.insort cut the loop from 4.2s to 0.14s on 50k inserts. The 5-line rewrite plus the keyed variant is here.

bisect Instead of sort() on Every Insert (Python)

I had a leaderboard insert loop running list.append + list.sort. Swapping to bisect.insort cut the loop from 4.2s to 0.14s on 50k inserts. The 5-line rewrite plus the keyed variant is here.

Python
Compiler
3 snippets
binary-search
performance
sorting
sarahwilson

By @sarahwilson

May 14, 2026

·

Updated May 18, 2026

935 views

21

4.4 (10)

The two loops produce identical output but with very different complexity. sort() on every insert is O(N log N) per call, so the loop is O(N^2 log N); bisect.insort is O(log N) for the lookup plus O(N) for the shift, so the loop is O(N^2). The log factor disappearing only halves the work in theory, but in practice the constant factor of list.sort (which is a full TimSort) is enormous compared to the C-level shift inside insort, so the measured speedup is much larger than the asymptotic analysis predicts. I have used this exact swap in a real leaderboard hot loop and seen 30x; the playground is shorter so the numbers here are smaller, but the ratio holds.