Set sorting?
As we know, the order of the elements in the set is not taken into account. So does it make sense to talk about sorting sets in Python 3?! (That's why there's a question mark in the title)
To quickly find an element in a set, it is desirable to store them in memory in an ordered form.
Let's look at some examples. What happens to elements of different data types in the same set? Such elements should not be sorted. If we print elements using the print()
command, they will be output like this:
a = {0, 1, 12, 'b', 'ab', 3, 2, 'a'}
print(a) # {0, 1, 2, 3, 'a', 12, 'b', 'ab'}
In this case, unsorted values are displayed. If you repeat the launch, then the output order may be different. But this is only if elements of different types are mixed.
Let's try to display data of one type (for example, only numbers):
a = {0, 1, 12, 3, 2}
print(a) # {0, 1, 2, 3, 12}
All elements are displayed in order. Let's try to convert it to a list:
a = {0, 1, 12, 3, 2}
b = list(a)
print(b) # [0, 1, 2, 3, 12]
Similarly, the elements sorted in ascending order were written to the list.
It turns out that elements are stored in memory in an ordered form if they are of the same type. But it's better not to count on it, Python algorithms can change.
If you need to get a sorted list from a set, it's better to use the sort
(sorted) function to be sure
). The elements will be exactly sorted. Your code will be understandable to others.