Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function to remove duplicates from a List | Python [duplicate]

Tags:

python

I am trying to write a function remove_duplicates to return only unique values from a list input. I tried to come up with some code but it is throwing infinite loop error. I am unable to understand why. The goal is not to achieve result as I have discovered there are direct methods like 'SET' to do this. But, I primarily wanted to understand my mistake as this is my first language and first day at any kind of coding.

def remove_duplicates(x):
    z = [x[0]]
    for i in range(1,len(x)):
        y = i-1
        k = 0
        while y >= 0:
            if x[i] == x[y]:
               k = k + 1 
               y -= 1
        else:
            break
        if k == 0:
            z.append(x[i])
    return z        
like image 332
Aman Dhoot Avatar asked Mar 01 '16 19:03

Aman Dhoot


2 Answers

Use the built-in python set capabilities.

y = list(set(x))

y will be a list of the unique elements of x. This works when the elements in x may be used in a set, so they have to implement __eq__() and __hash__().

like image 106
svohara Avatar answered Oct 04 '22 21:10

svohara


It'll be good If you can use

SET operator

to remove the duplicate elements from the list, like this:

my_list = [1, 2, 3, 1, 1, 1, 1, 1, 2, 3, 4]

Now time to remove the duplicate elements from this list:

list(set(my_list))

Answer: [1, 2, 3, 4]
like image 21
Talat Parwez Avatar answered Oct 04 '22 21:10

Talat Parwez