Recently I noticed that when I am converting list to set the order or elements is changed and is sorted by character.
Consider this example:
x=[1,2,20,6,210]
print x
# [1, 2, 20, 6, 210] # the order is same as initial order
set(x)
# set([1, 2, 20, 210, 6]) # in the set(x) output order is sorted
My questions are -
- Why is this happening?
- How can I do set operations (especially Set Difference) without losing the initial order?
In Python 3.6,there is another solution for Python 2 and 3:set()
now should keep the order, butAs denoted in other answers, sets are data structures (and mathematical concepts) that do not preserve the element order -
However, by using a combination of sets and dictionaries, it is possible that you can achieve wathever you want - try using these snippets:
Answering your first question, a set is a data structure optimized for set operations. Like a mathematical set, it does not enforce or maintain any particular order of the elements. The abstract concept of a set does not enforce order, so the implementation is not required to. When you create a set from a list, Python has the liberty to change the order of the elements for the needs of the internal implementation it uses for a set, which is able to perform set operations efficiently.
An implementation of the highest score concept above that brings it back to a list:
Tested (briefly) on Python 3.6 and Python 2.7.
Here's an easy way to do it:
Building on Sven's answer, I found using collections.OrderedDict like so helped me accomplish what you want plus allow me to add more items to the dict:
If you want to add items but still treat it like a set you can just do:
And you can perform an operation like z.keys() on the dict and get the set: