Converting a list to a set changes element order
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Ocean Floor
--
Chapters
00:00 Converting A List To A Set Changes Element Order
00:31 Accepted Answer Score 202
01:34 Answer 2 Score 31
02:04 Answer 3 Score 81
02:14 Answer 4 Score 54
02:29 Thank you
--
Full question
https://stackoverflow.com/questions/9792...
--
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.