5

So I notice that we say in python that sets have no order or arrangement, although of course you can sort the list generated from a set.

So I was wondering how the iteration over a set is defined in python. Does it just follow the sorted list ordering, or is there some other footgun that might crop up at some point?

Thanks.

user49404
  • 732
  • 6
  • 22
  • 1
    Maybe dupe (somewhat dated) ['order' of unordered Python sets](https://stackoverflow.com/q/12165200/674039) – wim Apr 17 '19 at 19:06
  • 2
    A *set* has no order; a set *iterator* imposes (an arbitrary) one. Whatever order you see, though, is an implementation detail and should not be relied on . – chepner Apr 17 '19 at 19:06
  • 1
    Python, the *language*, says nothing about it. And if you want to know about CPython, well, this is basically just a [RTFS](https://github.com/python/cpython/blob/master/Objects/setobject.c) question. – wim Apr 17 '19 at 19:10
  • 1
    Set do not have an order from the developers perspective. But of cause there is an order in memory, usually define by the hashing used for keying the set. This order can be used to iterate the set. How this happens in detail can be different per interpreter or even version. – Klaus D. Apr 17 '19 at 19:17
  • @wim or [more specifically the magic mostly happens here](https://github.com/python/cpython/blob/3092d6b2630e4d2bd200fbc3231c27a7cba4d6b2/Objects/setobject.c#L867) Essentially, they iterate over internal table using an index and a while-loop, skipping NULL and DUMMY entries. – juanpa.arrivillaga Apr 17 '19 at 19:22

1 Answers1

3

A temporary order is used to iterate over the set, but you can't reliably predict it (practically speaking, as it depends on the insertion and deletion history of the set). If you need a specific order, use a list.

Alec
  • 8,529
  • 8
  • 37
  • 63