0

Sets are called unordered collection of elements or items right? Then why it is ordered when I run integers in a set. When I run any strings, they will be ordered alphabetically. I do not understand this. Please explain

Ex 1: When we run

a = {"tammy", "rick", "morty"}  

it gives

{'morty', 'rick', 'tammy'}

which is in alphabetical order!

Ex 2: When we run

b = {23,56,43,76,856}

It gives

{23, 43, 56, 76, 856}

which is in ascending order!

paradocslover
  • 2,600
  • 3
  • 15
  • 38
  • 1
    "Unordered" means that it is not possible for two sets to differ by order in a meaningful sense. If you compare two sets with the same elements specified in different orders, you'll see that they're considered equal, because order is explicitly not significant in a set. – Samwise May 11 '21 at 06:43
  • 1
    This accidental ordering is not a part of set properties in Python and it only happens with small integers. – pavel May 11 '21 at 06:45
  • @pavel can you give an example where this does not hold true? – paradocslover May 11 '21 at 06:51
  • 1
    `b = {-97, 1}` => `{1, -97}` – Robby Cornelissen May 11 '21 at 06:54
  • @RobbyCornelissen I tried the same example but surprisingly, I see the ordering there as well! – paradocslover May 11 '21 at 07:05

2 Answers2

0

Having looked into the source code of python set here, I think it is due to the way sets are implemented. The hashing causes a certain level of order but this also means as the set size increases and the number of hash collisions increase, the order that you see, will disappear.

I did some experiments and here are my observations:

  1. Assume, you have a variable a = {1,-97}, then printing the variable a would give you {-97,1} (an ordered representation) but printing the elements one by one would give you any random order.
  2. Generating a random big set using
a = set([random.randint(10000, 1e15) for i in range(n)])

gives an ordering as explained in point 1 for n<=999, but starting from n=1000 the ordering vanishes.

NOTE: These are mere observations and not facts.

But to answer your question, I can say that what you are observing is not applicable for all sets!

paradocslover
  • 2,600
  • 3
  • 15
  • 38
-2

In case of strings sets store those in lexicographical order i.e nothing but in dictionary order

Vibhav Surve
  • 65
  • 1
  • 6