1

I've come across a strange sorting of the Set while working with the collection. I know that the Set should not be sorted, so I was puzzled by the first example where the thisSetInteger collection is sorted from smallest to largest. In the next example(thisSetIntegers1), after adding more than 4 elements, the collection is not sorted. If I add a String instead of an Integer, the values in the collection are sorted to random. How is this possible?

code:

thisSetIntegers = {4,15,2}
print(thisSetIntegers)

thisSetIntegers1 = {15,4,2,3,100,9,7}
print(thisSetIntegers1)

thisSetString = {"Python", "Java", "C#"}
print(thisSetString)

output

{2, 4, 15}
{2, 3, 100, 4, 7, 9, 15}
{'Python', 'Java', 'C#'}
Petr
  • 103
  • 6
  • 1
    Two words: "implementation-defined". An unordered type can have a de facto order based on the hashing algorithm used to store it, but that order is also allowed to change at-will without notice (or to disappear if the runtime adds a randomization factor to the hashing to make denial-of-service attacks harder, or to be different based on details of OS/architecture/memory layout/etc), so software that's written to depend on an order that the documentation says isn't guaranteed is buggy. – Charles Duffy Sep 14 '22 at 17:01
  • 1
    So, since your code would be buggy if you wrote it to rely on anything you think you know about the order, why look at / think about / care about it at all? Only documented guarantees exist; everything else is happenstance. – Charles Duffy Sep 14 '22 at 17:02
  • I am new into Python, I prefer C#. But in school I have to use Python, in my HW I have to use Set and that's why I ran into this problem. – Petr Sep 14 '22 at 17:06

0 Answers0