Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unordered collection - sets in python [duplicate]

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])
like image 554
user2990084 Avatar asked Apr 28 '15 15:04

user2990084


People also ask

Can sets in Python have duplicates?

Every set element is unique (no duplicates) and must be immutable (cannot be changed). However, a set itself is mutable.

What is a collection that is unordered unindexed and does not allow duplicate members in Python?

Set is a collection which is unordered and unindexed. No duplicate members.

What collections allow duplicate items in Python?

Tuple — A tuple is an immutable ordered collection that allows duplicate elements.

Which collection does not allow duplicate in Python?

Sets Sets are a collection that is unordered and unindexed. They are mutable (changeable) but do not allow duplicate values to be held.


1 Answers

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.
like image 170
Abhijit Avatar answered Sep 27 '22 23:09

Abhijit