I tried to write a function to remove duplicates from a list in Python.
But after I did this, I found that the list was sorted by converting it to a set and back to a list.
Here is the script:
>>> l = [9,10,10,11,1,1,1,22,2,2,2] >>> s = set(l) >>> s set([1, 2, 9, 10, 11, 22]) >>> l2 = list(s) >>> l2 [1, 2, 9, 10, 11, 22] >>> l2 = list(set(l)) >>> l2 [1, 2, 9, 10, 11, 22] >>>
The set s
ordered (at least when printing it).
Why is the set ordered?
And what is the temporary difficulty if I remove duplicates by running this:
def remove_duplicates(nums): return list(set(nums))
source share