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.
CodePudding user response:
without the _ = iter(my_set) the result is sorted also
>>> my_set = {2, 1, 3}
>>> my_set
{1, 2, 3}
CodePudding user response:
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
CodePudding user response:
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.
