I am coming learning python after working with c++ for a few years. In c++ when you insert into a set it orders the elements, I can't figure out why in python sometimes the set will order the elements and sometimes it does not. Here are a few examples:
a = set([3, 2, 1])
print(a)
prints: {1, 2, 3}
a = set([1, 2, 3])
print(a)
prints: {1, 2, 3}
a = set([5, 7, 9])
print(a)
prints: {9, 5, 7}
a = set([7, 9, 5])
print(a)
prints: {9, 5, 7}
a = set([5, 3, 7])
print(a)
prints: {3, 5, 7}
I don't know what's going on here, I know you can sort the set using sorted() but the way it originally stores the information doesn't make any sense to me.
That's interesting. Test that I've tried:
using 3 digits return is in order if you do not use a digit higher than 7.
using 5 digits it returns correct order.
a = set([4,2,7])
print(a)
Output:
{2, 4, 7}
a = set([4,6,8,10,7])
print(a)
Output:
{4, 6, 7, 8, 10}
Like other collections, sets support x in set, len(set), and for x in set. Being an unordered collection, sets do not record element position or order of insertion. Accordingly, sets do not support indexing, slicing, or other sequence-like behavior
https://docs.python.org/3.8/library/stdt...-frozenset
It hashes the elements, then uses the last N bits of the hash, where N depends on the size of the set. For the small set given, N is probably 3.
>>> format(hash(9) & 0x7, "b")
'1'
>>> format(hash(5) & 0x7, "b")
'101'
>>> format(hash(7) & 0x7, "b")
'111'
So the hash of 9 is smallest, 5, is next, then 7.
If the hash is identical, then order of insertion matters.
7 and 15 have the same hash value (in small sets).
>>> print(set((7, 15)))
{15, 7}
>>> print(set((15, 7)))
{7, 15}
There where discussion also about
sets
order,when in Python 3.7 modern
dict
where implement that are guarantee to keep order.
R. Hettinger Wrote:In short, the implementation of modern dicts that preserves insertion order is unique and not considered appropriate with sets.
In particular,dicts
are used everywhere to run Python (e.g. __dict__ in namespaces of objects).
A major motivation behind the modern dict was to reduce size, making Python more memory-efficient overall.
In contrast,sets
are less prevalent than dicts within Python's core and thus dissuade such a refactoring
Having unordered sets are consistent with a very generic and ubiquitous data structure that unpins most modern math, i.e. Set Theory.
I submit,unordered sets in Python are good to have.