When I read about sets in Python, it is always mentioned that they return items in an arbitrary/random order. What exactly causes this "randomness"?

  • 1
    Check out this SO question stackoverflow.com/questions/15479928/… – Nick Chapman Dec 13 '18 at 18:28
  • You can read more about it in the answer linked to above, but the significance of that statement is that the order is unspecified and implementation-dependent, and it can change, meaning that ordering (or, rahter, orderedness) is not part of the public API / contract, and that your own code shouldn't rely on it, or it could break. The statement more closely defines Set as a type. – Filip Milovanović Dec 13 '18 at 19:38
  • As someone who works with random I'm so much happier to see this not-defined-by-spec behavior described as arbitrary. – candied_orange Dec 14 '18 at 0:16
  • 1
    Note that "arbitrary" is something veeeeery different from "random". – Jörg W Mittag Dec 14 '18 at 11:20

It's not so much that they are random, but that since it is undefined, you should make no expectations as to what order they are in unless you specifically order it.

There are a variety of python interpreters. There are a lot in fact. When you add items to a list, the python interpreter is responsible for keeping track of the items. Each interpreter could keep track of them in different ways. The underlying storage mechanism could change from one version to the next of a single interpreter. It could change storage strategies based on the size of the list. It could change storage strategies based on the processor architecture, based on what day of the week it is, basically any criteria the interpreter developers decide is important.

So the advice to treat the order as random is to form the habit not to depend on a non-required behavior for your programs. Sure, chances are good that the order of a list is going to be the same as the order items are added, until suddenly it isn't and your program explodes. If you always mentally treat the order as arbitrary/random, you'll never be caught by surprise because you'll always explicitly order the list in whatever ordering is required for the task at hand.

  • In particular, if the set implementation uses hashing, then – depending on the hash function used – the ordering may be very non-obvious. – Jörg W Mittag Dec 14 '18 at 11:19

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.