Converting a list to a set changes element order
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 5 Looping
--
Chapters
00:00 Question
00:42 Accepted answer (Score 190)
01:56 Answer 2 (Score 80)
02:11 Answer 3 (Score 42)
02:30 Answer 4 (Score 30)
03:07 Thank you
--
Full question
https://stackoverflow.com/questions/9792...
Accepted answer links:
[set]: https://docs.python.org/library/stdtypes...
[collections.OrderedDict]: https://docs.python.org/library/collecti...
Answer 3 links:
[How to remove duplicates from a list while preserving order in Python]: http://www.martinbroadhurst.com/removing...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #set
#avk47
ACCEPTED ANSWER
Score 202
A
setis an unordered data structure, so it does not preserve the insertion order.This depends on your requirements. If you have an normal list, and want to remove some set of elements while preserving the order of the list, you can do this with a list comprehension:
>>> a = [1, 2, 20, 6, 210] >>> b = set([6, 20, 1]) >>> [x for x in a if x not in b] [2, 210]If you need a data structure that supports both fast membership tests and preservation of insertion order, you can use the keys of a Python dictionary, which starting from Python 3.7 is guaranteed to preserve the insertion order:
>>> a = dict.fromkeys([1, 2, 20, 6, 210]) >>> b = dict.fromkeys([6, 20, 1]) >>> dict.fromkeys(x for x in a if x not in b) {2: None, 210: None}bdoesn't really need to be ordered here – you could use asetas well. Note thata.keys() - b.keys()returns the set difference as aset, so it won't preserve the insertion order.In older versions of Python, you can use
collections.OrderedDictinstead:>>> a = collections.OrderedDict.fromkeys([1, 2, 20, 6, 210]) >>> b = collections.OrderedDict.fromkeys([6, 20, 1]) >>> collections.OrderedDict.fromkeys(x for x in a if x not in b) OrderedDict([(2, None), (210, None)])
ANSWER 2
Score 81
In Python 3.6, there is another solution for Python 2 and 3:set() now should keep the order, but
>>> x = [1, 2, 20, 6, 210]
>>> sorted(set(x), key=x.index)
[1, 2, 20, 6, 210]
ANSWER 3
Score 54
Remove duplicates and preserve order by below function
def unique(sequence):
seen = set()
return [x for x in sequence if not (x in seen or seen.add(x))]
How to remove duplicates from a list while preserving order in Python
ANSWER 4
Score 31
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.