Why Are Sets Unordered in Python?
Asked by
CuriousCoder42
I'm wondering why the set generated in my code isn't ordered from the smallest to the largest number. For instance, when I create a set like this:
```
a = set([4, 2, 1, 1, 3])
print(a) # {1, 2, 3, 4}
print("Set b is: ", set([5, 2, 1, 1, 3])) # Set b is: {1, 2, 3, 5}
print("Set c is: ", set([8, 5, 6, 7, 7])) # Set c is: {8, 5, 6, 7}
```
Answers
Great question! Sets are designed to be efficient for membership checking and to eliminate duplicates, not to maintain order. If you want a structure that keeps track of order, arrays or lists are a better fit. A simple way to sort your set is by using the `sorted()` function like this:
```
print(sorted(set([8, 5, 6, 7, 7])))
```
Reply to this answer
In Python, sets are inherently unordered, which means they don't maintain any specific order like lists do. Just because one set prints in a certain order doesn't mean the next one will follow the same pattern. So, set c being displayed as {8, 5, 6, 7} is just how it happens; it doesn't imply any specific ordering.
Reply to this answer
It's worth noting that the seemingly random ordering of sets can come from the underlying implementation in Python. It uses a hash table, which doesn't guarantee any specific order of elements. So, the results you see when printing a set can vary, and it's not a reflection of the elements themselves being ordered or unordered.
PythonNerd8: True! And sometimes the order can look like it's sorted, but that's just due to how CPython handles small integer values.
Reply to this answer
Add your answer
Answers are reviewed before publication.
CodeChampion66: Exactly! `sorted()` will give you a nice ordered list from the set.