0

I am bit confused. It starts like this.

  • You can add element into empty set using add() method.
  • Sets doesn't maintain the order in which the elements are added to set.
a=set()
b=[4,2,3]
for i in b:
  a.add(i)

Expected output is set([4, 2, 3])

But actual output is

C:\Users\dinesh_pundkar\Desktop>python dsp.py
set([2, 3, 4])

So I thought/assume, after adding element to set it got sorted that's why output is set([2,3,4]).

Now, I added alphabet 'A' to above set and output is set(['A', 2, 3, 4]).

To check whether this sorted or not, I created a list b = ['A', 2, 3, 4] and sorted it.

Eureka !!! Sorted list is [2,3,4,'A'].

So, that's why I am confused.

Requesting all to help me understand this or what I am missing.

Dinesh Pundkar
  • 4,160
  • 1
  • 23
  • 37
  • 1
    Elements in set are not ordered , and they are not inserted in sorted order. – ᴀʀᴍᴀɴ Jan 20 '17 at 10:36
  • Sets do not preserve (initial) order. – Willem Van Onsem Jan 20 '17 at 10:37
  • I think this explains -- set is a data structure optimized for set operations, and like a mathematical set, it does not enforce/maintain any particular order of the elements. The abstract concept of set does no enforce order, so does not the implementation. When you create a set from a list, python takes the liberty to change the order of the elements for the needs of the internal implementation it uses for a set, which is able to perform the set operations efficiently. – Dinesh Pundkar Jan 20 '17 at 10:38
  • @Jean-François Fabre - Can I add above explanation to my question? – Dinesh Pundkar Jan 20 '17 at 10:43

0 Answers0