Q: Why is the python set in different (random) order while printing? Why is not having the same order as that of insertion sequence?
A: Python sets are unordered, which means that they don’t preserve the order in which you insert elements. The sets are also non-indexable, meaning that you can access the n’th inserted element by
Q: Ok, but still, why does it not in the same order as what I am giving it?
A: It is because of the way Python sets are implemented. Internally, a python set uses a hash table to store the elements of the set. The hash table can be roughly thought as a dynamically resizable array containing your elements of the set arranged in an order based on something called a hash function.
Basically, to store an element say ‘hello’, we find the hash value of the element using the hash function.
Let us assume hash(‘hello’) = 36355 and let us assume your current hash table size is 7.
So you will store your element ‘hello’ at the location index 36355%7 = 4 in your hash table.
Another element say ‘world’ might get mapped to an index of 2 and get stored there in your hash table.
So this is a basic explanation behind why elements of a set are seemingly randomly arranged.
Q: Ok, I get it, but not completely. What is a hash table, what is a hash function, why do we store elements of a set that way instead of storing one by one like the Python list? What benefit bro?
A: I would request to check on how hash table works and benefits of using it to understand more. There will be many online resources to help you with that.