1

Why doesn't Python's set object have a sort() method?

>>> dir(set)
['__and__', '__class__', '__cmp__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__iand__', '__init__', '__ior__', '__isub__', '__iter__', '__ixor__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__or__', '__rand__', '__reduce__', '__reduce_ex__', '__repr__', '__ror__', '__rsub__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__xor__', 'add', 'clear', 'copy', 'difference', 'difference_update', 'discard', 'intersection', 'intersection_update', 'isdisjoint', 'issubset', 'issuperset', 'pop', 'remove', 'symmetric_difference', 'symmetric_difference_update', 'union', 'update']
mmary
  • 43
  • 1
  • 5

3 Answers3

6

Because a set is not ordered, by definition.

But you can get a sorted list from a set s using sorted(s).

Jesper
  • 1,611
  • 13
  • 10
2

Short answer from python doc.

https://docs.python.org/3.4/tutorial/datastructures.html#sets

A set is an unordered collection with no duplicate elements.

https://docs.python.org/2/library/sets.html

Since sets only define partial ordering (subset relationships), the output of the list.sort() method is undefined for lists of sets.


Long answer from Fluent Python Chapter 3 Dictionaries and Sets.

Understanding how Python dictionaries and sets are implemented using hash tables is helpful to make sense of their strengths and limitations.

#4: Key ordering depends on insertion order
#5: Adding items to a dict may change the order of existing keys
northtree
  • 8,569
  • 11
  • 61
  • 80
0

List.sort() established the convention that sort() sorts the object in place, but a set cannot be sorted in place because sets are unordered.

A set could conceivably have a method with another name that returned a sorted list of its elements. But there is no need for such a method because the function sorted() already does that job.

Bill Hees
  • 1
  • 1