Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python order of elements in set

Tags:

python

set

I do not understand the ordering what Python applies from holding sets. For example:

visited = set()
visited.add('C')
visited.add('A')
visited.add('B')
print(set)

The ordering is 'A', 'C', 'B'. Why 'A' is before 'C' (maybe alphabetical order)? What I have to do in order to preserve the adding ordering, i.e. 'C', 'A', 'B'?

like image 698
Bob Avatar asked Oct 17 '14 08:10

Bob


People also ask

Are elements in Python set sorted?

There are various methods to sort values in Python. We can store a set or group of values using various data structures such as list, tuples, dictionaries which depends on the data we are storing. So, in this article, we will discuss some methods and criteria to sort the data in Python.

Does order matter in a set Python?

Does set of list preserve order Python? A set is an unordered data structure, so it does not preserve the insertion order.

How do you find the order of an element in a list Python?

sort() method sorts the elements of a list in ascending or descending order using the default < comparisons operator between items. Use the key parameter to pass the function name to be used for comparison instead of the default < operator. Set the reverse parameter to True, to get the list in descending order.


2 Answers

You cannot have order in sets. and there is no way to tell how Python orders it. Check this answer for alternatives.

like image 198
avi Avatar answered Nov 04 '22 18:11

avi


Sets are different than lists. If you want to preserve an order, use a list. For example :

a = []
a.append('C')
a.append('A')
a.append('B')
print a # ['C', 'A', 'B']
like image 45
FunkySayu Avatar answered Nov 04 '22 16:11

FunkySayu