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,932
  • 3
  • 18
  • 44

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,932
  • 3
  • 18
  • 44
-2

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

Vibhav Surve
  • 73
  • 1
  • 6