0

I understand that Python sets are not ordered.

And the ordering of a list will not be preserved when converted to a set

My question is: why are the elements of a list reordered when converted (in some implementations).

It would seem an extra action to reorder the elements during conversion.

If nothing else, it does not seem there would be much overhead in preserving the order (for convenience).

Imhotep
  • 3
  • 1
  • Maybe this post can help - https://stackoverflow.com/questions/9792664/ – Daniel Hao Jan 21 '21 at 20:33
  • No. I understand that sets are not ordered (I actually researched the Stackoverflow forums as much as I could before posted the questions). – Imhotep Jan 23 '21 at 03:03

1 Answers1

0

Thats because sets are based on the Hash Table data structure, where records are stored in buckets using hash keys, and the order of items (when printed or converted to list) depends on the hashes, but internally the order doest matter. so it doesnt really bother to change the order, it just adds the item and creates a hash index for it. when you print the set it is probably printed according to the lexographical order of hashes, or something like that.

As you can see from the following, the list when created from a set, takes the same order of hashes of these items.

>>> s=set([5,4,3,7,6,2,1,0])
>>> s
{0, 1, 2, 3, 4, 5, 6, 7}
>>> list(s)
[0, 1, 2, 3, 4, 5, 6, 7]
Dr.venom
  • 48
  • 6
  • Thanks.I see where your going with your explanation, but still not seeing why converting from an ordered list to a set would result in reordering. – Imhotep Jan 23 '21 at 03:02
  • It might, if the ordered list was modified with inserted values, resulting in members stored in the hash table out of sequence (but still keyed sequentially). – Imhotep Jan 23 '21 at 03:10