-1

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 ?

kederrac
  • 16,819
  • 6
  • 32
  • 55
xelp
  • 47
  • 4
  • `bisect` needs a ordered list. – Daniel Mar 25 '20 at 20:28
  • 1
    @Daniel `a` is ordered, it's just in reverse order – xelp Mar 25 '20 at 20:29
  • 1
    I assume that by sorted (as per the docs), it is meant: sorted in increasing order. The documentation for the various functions (and parameter names) also hint at this. – 9769953 Mar 25 '20 at 20:33
  • @00 if this is the case, that's a BIG hole in the docs ... – xelp Mar 25 '20 at 20:34
  • Sure. You could file an issue for that. But for the moment, I think this also the assumption you'll to work with. – 9769953 Mar 25 '20 at 20:35
  • You can also deduce it from [the code itself](https://github.com/python/cpython/blob/3.8/Lib/bisect.py), linked in the docs. The code is even shorter than the full documentation. – 9769953 Mar 25 '20 at 20:37

1 Answers1

2

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).

kederrac
  • 16,819
  • 6
  • 32
  • 55
  • I don't think it's a valid answer/description . you can sort a bunch of numbers with the "less than" or "greater than" operator . That list IS sorted . – xelp Mar 25 '20 at 20:32
  • that list is reversed is a bit different – kederrac Mar 25 '20 at 20:34
  • how is different from sorting with a "less than operator" ? – xelp Mar 25 '20 at 20:35
  • @xelp now my answer is better? – kederrac Mar 25 '20 at 20:40
  • you may also havea look [here](https://stackoverflow.com/questions/2247394/bisect-is-it-possible-to-work-with-descending-sorted-lists) – kederrac Mar 25 '20 at 20:44
  • at this point I think they just forgot to mention the expected ordering ( ascending order ) in the docs and `insort` is only valid for ascending orders . – xelp Mar 25 '20 at 20:44