Why is the set ordered when converting the list to install?

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)) 
+5
source share
1 answer

The run time for the list(set(data)) approach is O (n).

A collection looks ordered like an artifact of how integers are hashed. With other inputs, the data will bounce off an ordered order.

To overcome arbitrary ordering, use this idiom, which is also O (n): list(collections.OrderedDict.fromkeys(data))

+6
source

Source: https://habr.com/ru/post/1245838/


All Articles