Sorry if this is a basic question , but i am trying to understand how set type works in python
From docs:
A set object is an unordered collection of distinct hashable objects.
Being an unordered collection, sets do not record element position or order of insertion.
But if they are unordered, why I am getting always the same order in this test? I am expecting some random order.
users_ids = set([1, 1, 2, 3])
>>> print users_ids
set([1, 2, 3])
Every set element is unique (no duplicates) and must be immutable (cannot be changed). However, a set itself is mutable.
Set is a collection which is unordered and unindexed. No duplicate members.
Tuple — A tuple is an immutable ordered collection that allows duplicate elements.
Sets Sets are a collection that is unordered and unindexed. They are mutable (changeable) but do not allow duplicate values to be held.
A random order is not unordered. Unordered means there is no defined way the data would be ordered i.e. the insertion order or the data does not have any correlation with how the data is arranged.
The reason the data is always in a predictable order because it so happened that the particular implementation have chosen to always arrange the elements in a manner such that the order of insertion dictates the data ordering. But, there is no guarantee# that would happen and we do see this deviating in 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 would still call it unordered, unless the documents strictly says so and provides guarantee of its order or there may be surprises waiting for you. I have seen implementations which relied on the fact that sets and dictionaries maintained ordered based in insertion pattern. Such implementations has serious consequences when they were ported to Python 3.X.
#
What’s New In Python 3.3
Security improvements: Hash randomization is switched on by default.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With