← All notes

Python bisect finds insertion points in sorted lists; insort inserts while keeping order

Answer: Use bisect_left(a, x) or bisect_right(a, x) to locate the insertion point for x in a sorted list, and insort(a, x) to insert x in sorted order. The functions are designed to locate an insertion point rather than search for a specific value, and they only call __lt__().

Examples

from bisect import bisect, bisect_left, insort

def grade(score):
    i = bisect([60, 70, 80, 90], score)
    return "FDCBA"[i]

[grade(s) for s in [33, 99, 77, 70, 89, 90, 100]]
# ['F', 'A', 'C', 'C', 'B', 'A', 'A']

def index(a, x):
    'Locate the leftmost value exactly equal to x'
    i = bisect_left(a, x)
    if i != len(a) and a[i] == x:
        return i
    raise ValueError

left vs right

The key parameter

The key parameter, added in version 3.10, extracts a comparison key from each element. To support searching complex records, the key function is not applied to the x value; for insort, it is applied to x for the search step only.

Performance and safety

See also

Claims

Sources

License: this note is CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Summary by iinventedlight (AI-assisted). Sources: Python docs, bisect — Array bisection algorithm; python/cpython (GitHub), Lib/bisect.py. PSF-2.0 (https://docs.python.org/3/license.html). Copyright Python Software Foundation. Text was condensed and changed from the originals.

License: CC-BY-4.0 · Summary by iinventedlight (AI-assisted). Sources: Python docs, bisect — Array bisection algorithm; python/cpython (GitHub), Lib/bisect.py. PSF-2.0 (https://docs.python.org/3/license.html). Copyright Python Software Foundation.

Cite this

Permanent ID: iil:note:375rscv1

iinventedlight. 2026. "Python bisect finds insertion points in sorted lists; insort inserts while keeping order." iinventedlight Library, iil:note:375rscv1, version of 2026-11-18. https://iinventedlight.com/library/notes/python-bisect/. License: CC-BY-4.0.

@misc{iil_note_375rscv1,
  author = {{iinventedlight}},
  title = {{Python bisect finds insertion points in sorted lists; insort inserts while keeping order}},
  howpublished = {iinventedlight Library},
  year = {2026},
  date = {2026-11-18},
  url = {https://iinventedlight.com/library/notes/python-bisect/},
  note = {Permanent ID iil:note:375rscv1. License: CC-BY-4.0.},
}

Markdown

Spotted a mistake? Use the MCP feedback tool or email hello@iinventedlight.com. Or Report a correction (no account needed).

For language models and agents: start at /llms.txt | /agents.md | /.well-known/agent-library.json. This page in Markdown: /library/notes/python-bisect.md.