2

If I create a set object and add some value to this and then I add another value (smaller than before) sometimes set sorts it and puts the new value on the begging and sometimes just ignore any orders and puts it on the very end of the set.

Here's example with sorting:

>>> x = set()
>>> x.add(10)
>>> x.add(1)
>>> x
{1, 10}
>>>

And here's the case I don't really understand:

>>> x = set()
>>> x.add(10)
>>> x.add(2)
>>> x
{10, 2}
>>>

Maybe set just do not sort values but why in the first case value 1 is putted on the beginning if I added it to set after 10 value. I don't really understand why it works like that. Sometimes it sorts a new added value and sometimes not.

pypy111
  • 25
  • 3
  • Sets in Python are Unordered. Refer this: https://stackoverflow.com/questions/12165200/order-of-unordered-python-sets – Ram Jun 13 '21 at 15:42
  • @Ram, but why does python add the `1` before the `10`? – Thavas Antonio Jun 13 '21 at 15:43
  • @BuddyBob Read the answers in the link that I shared earlier, you'll understand. You cannot conclude by just adding two numbers to the set. Try adding a mix of positive and negative numbers to the set and check if it's ordered/Unordered. – Ram Jun 13 '21 at 15:48
  • That's what I want to know. I figure it out that set is not sorted, but the first case in confusing. – pypy111 Jun 13 '21 at 15:48

1 Answers1

1

set is definitely not sorted. Keep that in mind that set is more complicated data structure than for example List. Here is a question which fits to yours: 'order' of unordered Python sets. You should definitely check it out.

blazej
  • 1,322
  • 4
  • 10
  • 19