Unordered collection - collection in python

Sorry if this is a basic question, but I am trying to understand how set type works in python

From the docs :

A given object is an unordered collection of different hashable objects.

As an unordered collection, sets do not record item position or insertion order.

But if they are unordered, why am I always getting the same order in this test? I expect some random order.

users_ids = set([1, 1, 2, 3])
>>> print users_ids
set([1, 2, 3])

      

+3


source to share


1 answer


Random order is not disordered. Unordered means that there is no specific way to order the data, i.e. the insertion order or the data has no correlation with how the data is ordered.

The reason the data is always in a predictable order is because it just so happens that a particular implementation has chosen to always order the elements in such a way that the order of insertion dictates the ordering of the data. But there is no guarantee # what will happen, and we will see this deviation in the Python 3.X dictionary implementation.

Note Even if we see that the data is sorted,

>>> {1,2,3,4,5}
set([1, 2, 3, 4, 5])

      



we will still call it disordered, unless the documents say strictly about it and warrant ordering it, or there may be surprises. I've seen implementations that relied on sets and dictionaries to be kept ordered by the insertion pattern. Such implementations have serious implications when ported to Python 3.X.

#

What's new in Python 3.3

Security improvements:
    Hash randomization is switched on by default.

      

+8


source







All Articles