2

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']
6
  • You can call sorted() on a set... Commented Feb 5, 2018 at 2:19
  • 6
    A set is by definition unordered. If you want an ordered collection, use a list. Commented Feb 5, 2018 at 2:20
  • What is wrong with sorted()? Commented Feb 5, 2018 at 2:20
  • docs.python.org/3/howto/sorting.html Commented Feb 5, 2018 at 2:20
  • 3
    Possible duplicate of Sorting a set of values Commented Feb 5, 2018 at 2:22

3 Answers 3

8

Because a set is not ordered, by definition.

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.