As commentators noted, regular Python lists are sorted in order and sorted efficiently (thanks, Timsort!), But donβt remember and do not save the sort status.
If you need lists that invariably maintain their sorted status, you can install the SortedContainers package from PyPI .
>>> from sortedcontainers import SortedList >>> L = SortedList([3,4,2,1,5]) >>> L SortedList([1, 2, 3, 4, 5]) >>> L.add(3.3) >>> L SortedList([1, 2, 3, 3.3, 4, 5])
Note that the regular append method becomes add because the element is not added to the end. He added, where necessary, in sorting order. There is also a SortedListWithKey type that allows you to explicitly specify your key / sort order.
source share