Type set in Python is ordered?

2

When creating a variable like this:

a = {1,2,5,1,3}

It ends up returning a variable of type set . However, in the Python documentation, it is said that it is impossible to create a set without the set() function. Also, set has no order, but displaying the variable results in the numbers in ascending order.

What is a set?

    
asked by anonymous 06.06.2017 / 15:36

1 answer

5

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
    
06.06.2017 / 16:06