Type set in Python is ordered?

Asked

Viewed 896 times

4

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 function set(). Moreover, set has no order, but by displaying the variable I get the numbers in ascending order.

What is a set?

Show 2 more comments

1 answer

7

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
  • 2

    The confusion of terms is very common, I learned wrong, I spent my whole life using wrong and even today I have difficulty using right, but since I learned, I try :)

  • I think the confusion is usually because in Portuguese we use the "ordered" for a set that follows a certain order. I also spent my life thinking they were the same thing, until I saw your question/answer and went to research more about it.

  • Yes, I think until in other areas exchange without problems. At least you saw that I can make a mistake, but I don’t come out saying nonsense around :D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.