# 🐍 Python - *bisect*

*bisect*

Updated at 2018-11-19 17:56

Bisection module allows you to efficiently add items to a **sorted** list so that you don't have to resort it.

```
import bisect
numbers = [1, 2, 4, 8]
bisect.insort(numbers, 5)
assert numbers == [1, 2, 4, 5, 8]
bisect.insort(numbers, 5)
assert numbers == [1, 2, 4, 5, 5, 8]
# but it won't work if the list is not sorted
integers = [4, 5, 3, 8]
bisect.insort(integers, 4)
assert integers == [4, 5, 3, 4, 8] # doesn't really do much, eh
```

Useful in two main cases:

- the list is massive
- the comparison operation is expensive

# Source

- Python 3 Documentation