1

Calling iter() on a set in Python seems to sort the set in place.

Example:

>>> my_set = {2, 1, 3}
>>> _ = iter(my_set)
>>> my_set
{1, 2, 3}

I am wondering why is that's the case. I guess it has something to do with the way __iter__ or __next__ are implemented for set in cPython but I am not sure.

Any idea is welcome.


EDIT

As pointed by answers and comments below, the _ = iter(my_set) does not change the results - my_set prints 'ordered'. The reasons are explained in details here.

ldc
  • 306
  • 1
  • 14
  • 2
    And what do you get if you eliminate the `_ = iter(my_set)`? – Fred Larson Jan 06 '22 at 19:07
  • 2
    `iter` has nothing to do with it, I achieve the same result with `new_set={2,1,3};new_set` which outputs `{1, 2, 3}`. I would imagine it's more to do with how a (unordered) set is built in the first place – G. Anderson Jan 06 '22 at 19:07
  • 1
    See [here](https://stackoverflow.com/a/45589593/6273251) for what seems like a decent explanation; specifically, the part about "well-defined hash order". It's not actually getting sorted at all. There's no guarantee of order whatsoever, but a set of numbers can happen to look sorted, it seems. They give an example of a set where it does not get "sorted" - `{6,7,8,9}` prints as `{8, 9, 6, 7}` – Random Davis Jan 06 '22 at 19:09
  • See https://stackoverflow.com/questions/12165200/order-of-unordered-python-sets – PM 77-1 Jan 06 '22 at 19:10
  • The order of items within a set should be considered as unreliable and, indeed, irrelevant. As to your specific question... there is no way that *iter()* would modify the value(s) referred to by its first parameter. Consider the implications if it did! – DarkKnight Jan 06 '22 at 19:14
  • @PM77-1: thank you very much for the link, super useful ! – ldc Jan 06 '22 at 19:51
  • 1
    @RandomDavis: Thank you very much for the link ! – ldc Jan 06 '22 at 19:52

3 Answers3

2

without the _ = iter(my_set) the result is sorted also

>>> my_set = {2, 1, 3}
>>> my_set
{1, 2, 3}
S4eed3sm
  • 1,398
  • 5
  • 20
1

Sets are unordered, which means they can appear in different orders when you call them. See more here: https://www.w3schools.com/python/python_sets.asp

Cameron
  • 389
  • 1
  • 9
1

As stated by @S4eed3sm, using the {} creates a set which becomes unordered. However, that's not the point of the iterator.

By using an iterator, you can call the next() method on the iterator to get the next item in the iterator. That's the purpose of the iterator, not sorting the set.

In case you want to sort a list, for example, you can use the sorted() method which is also built-in in python.

Kypps
  • 326
  • 2
  • 5