python - Are sets internally sorted, or is the __str__ method displaying a sorted list? -


i have set, add items (ints) it, , when print it, items apparently sorted:

a = set() a.add(3) a.add(2) a.add(4) a.add(1) a.add(5)  print # set([1, 2, 3, 4, 5]) 

i have tried various values, apparently needs ints.

i run python 2.7.5 under macosx. reproduced using repl.it (see http://repl.it/tpv)

the question is: documented somewhere (haven't find far), normal, can relied on?

extra question: when sort done? during print? internally stored sorted? (is possible given expected constant complexity of insertion?)

this coincidence. data neither sorted nor __str__ sort.

the hash values integers equal value (except -1 , long integers outside sys.maxint range), increases chance integers slotted in order, that's not given.

set uses hash table track items contained, , ordering depends on hash value, and insertion , deletion history.

the how , why of interaction between integers , sets implementation details, , can vary version version. python 3.3 introduced hash randomisation types, , python 3.4 expanded on this, making ordering of sets , dictionaries volatile between python process restarts (depending on types of values stored).


Comments

Popular posts from this blog

database - VFP Grid + SQL server 2008 - grid not showing correctly -

jquery - Set jPicker field to empty value -

.htaccess - htaccess convert request to clean url and add slash at the end of the url -