-2
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?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • 1
    That doesn't do any sorting. What specifically do you not understand about its operation? – jonrsharpe Jul 27 '18 at 08:22
  • Possible duplicate of [What does "list comprehension" mean? How does it work and how can I use it?](https://stackoverflow.com/questions/34835951/what-does-list-comprehension-mean-how-does-it-work-and-how-can-i-use-it) – Mr. T Jul 27 '18 at 08:27
  • Do you understand what `if not x[i] in x[:i]` means? – PM 2Ring Jul 27 '18 at 08:31
  • @PM2Ring I don't,can you explain that part? thanks – Abhijith Neil Abraham Jul 27 '18 at 21:35
  • `x[:i]` creates a slice of `x` that contains all of the items in `x` before `x[i]`. So `x[i] in x[:i]` is true if there's a duplicate of `x[i]` before `x[i]` itself. – PM 2Ring Jul 28 '18 at 03:53

1 Answers1

2

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.

RandomDude
  • 1,101
  • 18
  • 33
  • 1
    2nd approach does not sort the output, sets are unordered, and the list() call does not sort, for integers the output may appear ordered but this is just a quirk of the implementation – Chris_Rands Jul 27 '18 at 08:46