CodingMans
CodingMans

Reputation: 5

How does union() organize the set values?

When I have two sets and I use the union function to join them together, should the numbers be ordered from lower to highest? If not, how does python organize the number in the sets when joined together.

setA = {1,2,3}

SetB = {3,400,340,23}

print(setA.union(SetB))

The output is {400, 1, 2, 3, 340, 23} which is not ordered so I was wondering how the union function organises the numbers.

Upvotes: 0

Views: 41

Answers (1)

Alex W
Alex W

Reputation: 38183

From the documentation for sets:

A set object is an unordered collection of distinct hashable objects.

So the objects in a set cannot be assumed to be ordered and for all intents and purposes you should assume that they are not. Any semblance of ordering that you see is likely the result of comparing the hash values of the objects in the set.

You can see the code here: https://github.com/python/cpython/blob/master/Objects/setobject.c

Upvotes: 1

Related Questions