Ordering python sets

Roy Smith roy at panix.com
Wed Oct 22 10:30:52 EDT 2008


In article <mailman.2839.1224683382.3487.python-list at python.org>,
 Mr.SpOOn <mr.spoon21 at gmail.com> wrote:

> It seems to me that it orders elements when you add using the add()
> method, but if you create a set starting from a list, it may result
> unordered.

Arrrggghhh!  None of these behaviors are guaranteed.  The docs say, "A set 
object is an unordered collection".  If you write code which depends on a 
set preserving order, are going to get burned.

If you want something that preserves order, use a list.  If the O(n) lookup 
time of a list is too slow, you can get O(log n) with heapq.

If you truly need O(1) lookup time AND need to preserve order, you might 
consider writing a class which does something like stores the values in a 
list, but use a dict to map value -> list_index, and maintains both data 
structures in parallel.  Or, roll your own tree structure.  Or wait for 
true STL-style trees to be added to Python :-)



More information about the Python-list mailing list