Why are elements in Python set not ordered? - Week 5: Python: Sets

Please see the code where I create the set and print it

batsmen = {"Rohit","Virat","Ravindra","Rahul"}
print(batsmen)

I get the following output

{'Ravindra', 'Virat', 'Rohit', 'Rahul'}

The order in which they are displayed is different.

Similarly, when I print the union of two sets, it is displayed in random order. Please explain why?

players = batsmen.union(bowlers)
print(type(players))
print(players)

I get the following output

{'Bumrah', 'Rohit', 'Rahul', 'Ravindra', 'Virat', 'Ishant'}

Your code is Fine.
But you have to keep in your mind that Set did not hold Index order.
I mean that Like List,set did not hold indexing.
If you want to see a element is available or not,you can use" in" function.

My question is with respect to the order in which it is displayed. Does it mean that every time I display a set, the order of the elements will be different?

Any other response to the query?

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 set_variable[n-1].


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.

1 Like

Thanks @GokulNC for such an elaborate answer.