Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does python have a sorted list?

By which I mean a structure with:

  • O(log n) complexity for x.push() operations
  • O(log n) complexity to find an element
  • O(n) complexity to compute list(x) which will be sorted

I also had a related question about performance of list(...).insert(...) which is now here.

like image 390
ilya n. Avatar asked Jul 10 '09 14:07

ilya n.


People also ask

Is Python list sorted by default?

Since the name is a string , Python by default sorts it using the alphabetical order. For the second case, age ( int ) is returned and is sorted in ascending order. For the third case, the function returns the salary ( int ), and is sorted in the descending order using reverse = True .

Does Python have sorted set?

The sorted() function is a built-in function in Python that returns a sorted sequence (list,tuple,string) or sorted collection(sets,dictionary) in the form of a list. The sorted() function has no effect on the original iterable sequence as it provides a new sorted output.

How do you sort a list in Python?

The easiest way to sort is with the sorted(list) function, which takes a list and returns a new list with those elements in sorted order. The original list is not changed. It's most common to pass a list into the sorted() function, but in fact it can take as input any sort of iterable collection.


2 Answers

Is there a particular reason for your big-O requirements? Or do you just want it to be fast? The sortedcontainers module is pure-Python and fast (as in fast-as-C implementations like blist and rbtree).

The performance comparison shows it benchmarks faster or on par with blist's sorted list type. Note also that rbtree, RBTree, and PyAVL provide sorted dict and set types but don't have a sorted list type.

If performance is a requirement, always remember to benchmark. A module that substantiates the claim of being fast with Big-O notation should be suspect until it also shows benchmark comparisons.

Disclaimer: I am the author of the Python sortedcontainers module.


Installation:

pip install sortedcontainers 

Usage:

>>> from sortedcontainers import SortedList >>> l = SortedList() >>> l.update([0, 4, 1, 3, 2]) >>> l.index(3) 3 >>> l.add(5) >>> l[-1] 5 
like image 90
GrantJ Avatar answered Sep 30 '22 19:09

GrantJ


The standard Python list is not sorted in any form. The standard heapq module can be used to append in O(log n) to an existing list and remove the smallest one in O(log n), but isn't a sorted list in your definition.

There are various implementations of balanced trees for Python that meet your requirements, e.g. rbtree, RBTree, or pyavl.

like image 30
Martin v. Löwis Avatar answered Sep 30 '22 18:09

Martin v. Löwis