8

I do not understand the ordering that Python applies to 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'?

Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
Bob
  • 10,427
  • 24
  • 63
  • 71

2 Answers2

7

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

Community
  • 1
  • 1
avi
  • 9,292
  • 11
  • 47
  • 84
0

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']
FunkySayu
  • 7,641
  • 10
  • 38
  • 61