jeudi 5 juillet 2018

Unable to create duplicate list from existing list using list comprehension with an if condition

I have a sorted list with duplicate elements like

>>> randList = [1, 2, 2, 3, 4, 4, 5]
>>> randList
[1, 2, 2, 3, 4, 4, 5]

I need to create a list that removes the adjacent duplicate elements. I can do it like:

>>>> dupList = []
     for num in nums:
       if num not in dupList:
         dupList.append(num)

But I want to do it with list comprehension. I tried the following code:

>>> newList = []
>>> newList = [num for num in randList if num not in newList]

But I get the result like the if condition isn't working.

>>> newList
[1, 2, 2, 3, 4, 4, 5]

Any help would be appreciated. Thanks!!

Aucun commentaire:

Enregistrer un commentaire