Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a set display in same order if sets are unordered?

I'm taking a first look at the python language from Python wikibook.

For sets the following is mentioned:

We can also have a loop move over each of the items in a set. However, since sets are unordered, it is undefined which order the iteration will follow.

and the code example given is :

s = set("blerg")

for letter in s:
     print letter

Output:

 r b e l g

When I run the program I get the results in the same order, no matter how many times I run. If sets are unordered and order of iteration is undefined, why is it returning the set in the same order? And what is the basis of the order?

like image 620
palerdot Avatar asked Feb 11 '14 12:02

palerdot


People also ask

Are sets ordered or unordered?

Sets are unordered. Set elements are unique. Duplicate elements are not allowed. A set itself may be modified, but the elements contained in the set must be of an immutable type.

What does it mean that sets are unordered?

Unordered means when we display the elements of a set, it will come out in a random order. Unindexed means, we cannot access the elements of a set using the indexes like we can do in list and tuples. The elements of a set are defined inside curly brackets and are separated by commas.

Does converting an object to a set maintain the order?

1. Does converting an object to a set maintain the object's order? No. A set is not an ordered data structure, so order is not maintained.

Does order matter in a set Python?

Set in Python is a data structure equivalent to sets in mathematics. It may consist of various elements; the order of elements in a set is undefined.


1 Answers

They are not randomly ordered, they are arbitrarily ordered. It means you should not count on the order of insertions being maintained as the actual internal implementation details determine the order instead.

The order depends on the insertion and deletion history of the set.

In CPython, sets use a hash table, where inserted values are slotted into a sparse table based on the value returned from the hash() function, modulo the table size and a collision handling algorithm. Listing the set contents then returns the values as ordered in this table.

If you want to go into the nitty-gritty technical details then look at Why is the order in dictionaries and sets arbitrary?; sets are, at their core, dictionaries where the keys are the set values and there are no associated dictionary values. The actual implementation is a little more complicated, as always, but that answer will suffice to get you most of the way there. Then look at the C source code for set for the rest of those details.

Compare this to lists, which do have a fixed order that you can influence; you can move items around in the list and the new ordering would be maintained for you.

like image 183
Martijn Pieters Avatar answered Sep 19 '22 01:09

Martijn Pieters