3

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"?

asked Dec 13, 2018 at 18:02
4
  • 1
    Check out this SO question stackoverflow.com/questions/15479928/… Commented Dec 13, 2018 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. Commented Dec 13, 2018 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. Commented Dec 14, 2018 at 0:16
  • 1
    Note that "arbitrary" is something veeeeery different from "random". Commented Dec 14, 2018 at 11:20

1 Answer 1

5

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.

answered Dec 13, 2018 at 20:11
2
  • 1
    In particular, if the set implementation uses hashing, then – depending on the hash function used – the ordering may be very non-obvious. Commented Dec 14, 2018 at 11:19
  • Why are you talking about lists instead of sets? Commented Oct 25, 2024 at 15:34

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.