Performance comparison (transfer from http://www.linuxidc.com/Linux/2012-07/66404.htm)
I knew it was more efficient to use set in Python, but I didn't think there was such a big gap:
~$ python-m Timeit-n "[x for X in range (+) if x in range (500, 1500)]"
Loops, Best of 3:28.2 msec per loop
~$ python-m Timeit-n "set (range). Intersection (range (500, 1500))"
Loops, Best of 3:120 usec per loop
The List is about 225 times times the set time. List-to-set does not have much time, so it is best to use set when there is a need to ask for the set and intersection of (collections, lists, etc.).
Update
Considering that range (500, 1500) was called 1000 times (which would be time-consuming), it was changed to only one call, and the time dropped from 28.2msec to 18.2msec. It's still about 150 times times slower (than set).
~$ python-m timeit-n "Range1500=range (500, 1500); [x for X in range (+) if x in range1500] "
---------------------------------------------------------------------------------------
The set is converted to the list method as follows: The list is converted to the Set method as follows:
s = set (' 12342212 ') L = [' 12342212 ']
Print S # set ([' 1 ', ' 3 ', ' 2 ', ' 4 ']) s = set (L[0])
l = List (s) Print s # set ([' 1 ', ' 3 ', ' 2 ', ' 4 '])
L.sort () # Sort m = [' 11 ', ' 22 ', ' 33 ', ' 44 ', ' 11 ', ' 22 ']
Print L # [' 1 ', ' 2 ', ' 3 ', ' 4 '] print set (m) # set ([' 11 ', ' 33 ', ' 44 ', ' 22 '])
Visible set and lsit can be freely converted, when deleting multiple/massive duplicate elements in the list,
You can convert to set and then back to list and sort (set is not sorted). This method is not only convenient but also highly efficient.
Reprint: Python list and set performance comparison + both conversion