Search code examples
pythonsortinginsertionbisection

Weird behaviour of bisect.insort in Python 3


Python 3.8.2 on a linux box, If I create a list and just use insort over it, I get the expected result; on the other hand if I reverse the order of the elements in the container before calling insort this happens

>>> a = list(range(10))
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a.reverse()
>>> a
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
>>> bisect.insort(a,6)
>>> a
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 6]

I was expecting [9, 8, 7, 6, 6, 5, 4, 3, 2, 1, 0] not that.

Why it's producing this result ?


Solution

  • from the docs:

    This module provides support for maintaining a list in sorted order without having to sort the list after each insertion.

    also from the docs:

    Unlike the sorted() function, it does not make sense for the bisect() functions to have key or reversed arguments because that would lead to an inefficient design (successive calls to bisect functions would not “remember” all of the previous key lookups).