I think an example says it all about why I'm confused:
L=set()
L.add("A")
L.add("C")
L.add("B")
L
Out[6]: {'A', 'B', 'C'}
print(L)
{'B', 'C', 'A'}
Sorry for not respecting PEP8 in my example. Thanks!
EDIT : I'm using PyCharm and Python 3.10.2
I think an example says it all about why I'm confused:
L=set()
L.add("A")
L.add("C")
L.add("B")
L
Out[6]: {'A', 'B', 'C'}
print(L)
{'B', 'C', 'A'}
Sorry for not respecting PEP8 in my example. Thanks!
EDIT : I'm using PyCharm and Python 3.10.2
Sets are not ordered in python. In CPython your example also shows:
Python 3.9.9 | packaged by conda-forge | (main, Dec 20 2021, 02:36:06) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> L=set()
>>> L.add("A")
>>> L.add("C")
>>> L.add("B")
>>> L
{'C', 'B', 'A'}
>>> print(L)
{'C', 'B', 'A'}
In IPython on the other hand there is a custom display logic that sorts the output.
When using PyCharm it automatically recognizes an installed IPython in the respective environment and uses this for the console output.
Python sets are not ordered
Being an unordered collection, sets do not record element position or order of insertion.
Sets are implemented via hash tables, as opposed to a list-like data structure. The difference being that you can look up an item in constant time. That is, the value of the object determines where it's placed in the set (it's slightly more complicated, so the exact placement in fact also depends on the insertion order...).
A similar thing is going on with dictionaries.
While print(L)
shows you the actual data layout of the set in memory, the automatic Out[]
display of Ipython/Jupyter use a custom printing method, which apparently sorts sets before printing. See the link in the comment by Ryan Haining for some more detail.
A somewhat different thing you might notice is that the order changes whenever you run your program. This is because the hashes are salted, which in turn makes it harder to hack your code based on raw views of the memory. This can be disabled if you want, to always get the same ordering. On Linux/Mac, you can do this by running
export PYTHONHASHSEED=0
before running Python.