Ordering python sets

Tim Chase python.list at tim.thechases.com
Wed Oct 22 09:07:36 EDT 2008


> I think that using Python sets would be the best choice, but I also
> need integers to be ordered inside the set and I've just found out
> that, instead, Python sets are unordered collections.

Sets (both in Python, and their mathematical definition) are 
unordered.  However, some simple testing in my current python 
seems to indicate that both their repr() and their __iter__() 
seem to traverse in sorted order (though that may be a niceness 
that Python performs in 2.3 and above).  You can just order them 
when you go to operate on them:

   import random as r

   # to test in <2.4
   from sets import Set as set
   s = set([r.randint(1,1000) for _ in range(1000)])
   # for 2.4+
   s = set(r.randint(1,1000) for _ in range(1000))

   print s
   for i in sorted(list(s)):
     do_something(i)

Though for each test, in 2.3, 2.4, and 2.5 that I've got 
installed on my local machine, they each printed "s" in-order, 
and the iteration occurred in-order as well, even without the 
added "sorted(list(s))" code.

-tkc






More information about the Python-list mailing list