0
a = {1, 2, 3, 4, 5}
a.add(23)
a
{1, 2, 3, 4, 5, 23}
a.add(224)
a
{224, 1, 2, 3, 4, 5, 23}
a.add(300)
a
{224, 1, 2, 3, 4, 5, 23, 300}

How does python order elements in a set? 224 is placed in the first place when I add it to the set but 23 and 300 was place in the end of the set.

charlietfl
  • 170,828
  • 13
  • 121
  • 150
  • 1
    Does this answer your question? [Converting a list to a set changes element order](https://stackoverflow.com/questions/9792664/converting-a-list-to-a-set-changes-element-order) – bbnumber2 Mar 28 '21 at 04:05
  • 1
    The Python language does not specify an iteration order for sets (as is appropriate; the mathematical concept of a set is intrinsically unordered). If the implementation happens to have an order, that's implementation-defined and subject to change without notice; software should be written on the assumption that the order is completely uncontrolled and unpredictable. – Charles Duffy Mar 28 '21 at 04:11

1 Answers1

2

Python sets are not ordered so "you cannot be sure in which order the items will appear". Unordered-ness is an intrinsic property of a set, and if you need something ordered a set is not what you want. Perhaps a tuple or list would be better if you need ordered items.

JT Raber
  • 31
  • 3