Sets are not ordered, they are not ordered containers, so nothing you can do,
If you have a list and you want to use set then convert back to list in ordered way:
print(sorted(set(l),key=l.index))
So no chance of making ordered set
Btw, there is a ordered set...
link to download file, or just copy the code in a module and import it, remember to remove the if __name__ == '__main__'
part in the bottom
Or pip install boltons
, then:
from boltons.setutils import IndexedSet
Then example:
>>> from boltons.setutils import IndexedSet
>>> x = IndexedSet(list(range(4)) + list(range(8)))
>>> x
IndexedSet([0, 1, 2, 3, 4, 5, 6, 7])
>>> x - set(range(2))
IndexedSet([2, 3, 4, 5, 6, 7])
>>> x[-1]
7
>>> fcr = IndexedSet('freecreditreport.com')
>>> ''.join(fcr[:fcr.index('.')])
'frecditpo'
See link
Or pip install sortedcontainers
:
Once installed you can simply:
from sortedcontainers import SortedSet
help(SortedSet)
Or install collections_extended
Then example:
>>> from collections_extended import setlist
>>> sl = setlist('abracadabra')
>>> sl
setlist(('a', 'b', 'r', 'c', 'd'))
>>> sl[3]
'c'
>>> sl[-1]
'd'
>>> 'r' in sl # testing for inclusion is fast
True
>>> sl.index('d') # so is finding the index of an element
4
>>> sl.insert(1, 'd') # inserting an element already in raises a ValueError
ValueError
>>> sl.index('d')
4
See link