y=[ x[i] for i in range(len(x)) if not x[i] in x[:i] ]
Can anyone explain to me how this step by step approach of deleting duplicates and sorting them in an ascending order both works at the same time in this single line?
y=[ x[i] for i in range(len(x)) if not x[i] in x[:i] ]
Can anyone explain to me how this step by step approach of deleting duplicates and sorting them in an ascending order both works at the same time in this single line?
It simply adds each element to a new list in case the element was not in the part of the list that already was processed by the for loop. NO sorting is happening.
It looks a bit clearer when you write the loop like this:
lst = [5,5,5,1,2,3,4,]
[x for i, x in enumerate(lst) if x not in lst[:i]]
>>> [5, 1, 2, 3, 4]
enumerate()
returns the index as well as the element.
A much faster approach in python:
sorted(set(lst))
>>> [1, 2, 3, 4, 5]
Update
as Chris_Rands stated out set()
is not sorted. Using sorted()
will return a list of sorted elements.