You’re confusing the terms unordered
and sorted
. Maniero’s question explains very well each term:
What is the difference between ordered, unordered and Sorted?
For more details about what is and when to use a set
, see the discussion in:
What’s the set for in Python?
Just because an example you tested returned a 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 they are all in the same order as your 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 on Ideone.
See the number of sets that were created that were not sorted as you expected. The order that is returned is a 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 guy set
also has no index, that is, 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
In the documentation: "Curly braces or the set() Function can be used to create sets.". That is, it is possible, yes, to create a
set
with{}
.– Woss
Still, "A set is an unordered Collection with no Duplicate Elements", so it should not have order. Why I get a set in ascending order?
– Gabriel Lima
Related: What is the difference between ordered, unordered and Sorted?
– Woss
Related: What’s the set for in Python?
– Woss
Possible duplicate of What’s the set for in Python?
– Jéf Bueno
Therefore, unordered only means that I cannot access the index?
– Gabriel Lima
It means that there are no guarantees as to the order of the results.
– Woss