You are confusing the terms unordered
and sorted
. The bigown question explains each term very well:
What's the difference between ordered, unordered and sorted?
For more details on what and when to use set
, see the discussion at:
What is the set used for in Python?
Just because an example you tested returned an assorted set does not mean that the type will always be assorted.
Take a very simple test:
Generate a large number of sets with random values and check that all are in the same order as their respective assorted list.
import random
# Efetua 1000 testes:
for _ in range(1000):
# Gera um conjunto de 10 números inteiros entre 0 e 9:
a = set(random.randint(0, 9) for __ in range(10))
# Verifica se o conjunto é igual à sua respectiva lista sortida:
if list(a) != sorted(a):
# Se for diferente, exibe o conjunto:
print(a)
See working at Ideone .
See how many sets were created that did not look the way you expected them to. The order that is returned set
will depend on the internal implementation in the language and there is no guarantee that these values will be assorted or always in the same order in all environments. The type set
also has no index, ie it is not possible to access a certain position through the index:
a = {1, 2, 5, 1, 3}
print(a[0])
Returns the error:
Traceback (most recent call last):
File "python", line 3, in <module>
TypeError: 'set' object does not support indexing