Insert an item into sorted list in Python
Use the insort function of the bisect module: import bisect a = [1, 2, 4, 5] bisect.insort(a, 3) print(a) Output [1, 2, 3, 4, 5]
Use the insort function of the bisect module: import bisect a = [1, 2, 4, 5] bisect.insort(a, 3) print(a) Output [1, 2, 3, 4, 5]
Yes, the intention of the manual is indeed to guarantee that sorted is stable and indeed that it uses exactly the same algorithm as the sort method. I do realize that the docs aren’t 100% clear about this identity; doc patches are always happily accepted!
If you are using numpy, you have the argsort() function available: >>> import numpy >>> numpy.argsort(myList) array([0, 1, 2, 4, 3]) http://docs.scipy.org/doc/numpy/reference/generated/numpy.argsort.html This returns the arguments that would sort the array or list.