0

So I was converting a list with repetitive elements into a set to have each element appear once. I know that sets are unordered so they will display the elements in the order given. I ran the below script and I noticed a strange output.

mylist = [1,2,2,33,4,4,11,22,3,3,2]

print(set(mylist))

The output would be:

{1, 2, 33, 4, 3, 11, 22}

The 3 in the original list appears after the 11 and 22, so why does it appear before them in the set?

  • It depends on how typecasting is performed by python. Seems like converting to a set appends new elements at the end while rejecting one that exists in set. – PaxPrz Jan 01 '20 at 03:17
  • `..so they will display the elements in the order given.` - what makes you think that? – wwii Jan 01 '20 at 03:35
  • Related: https://stackoverflow.com/questions/12165200/order-of-unordered-python-sets – wwii Jan 01 '20 at 03:42
  • Also, cannot reproduce. – wwii Jan 01 '20 at 03:43

1 Answers1

3

Sets in Python do not have an order

A set object is an unordered collection of distinct hashable objects. Common uses include membership testing, removing duplicates from a sequence, and computing mathematical operations such as intersection, union, difference, and symmetric difference.

https://docs.python.org/3/library/stdtypes.html#set-types-set-frozenset

whackamadoodle3000
  • 6,684
  • 4
  • 27
  • 44