1

I am a beginner learning Python and was trying to remove duplicates from list while using any (Trying to learn any() and all()).

def remove_duplicates(x):
    l=0
    for i,item in enumerate(x):
        if any(l==item for l in x)==True:
            print (i,item)
            x=del x[i]
    return(x)
x=[1,2,3,1]
print (remove_duplicates(x))

I am getting the following result.

0 1
1 3
[2, 1]

Instead of [2,3,1].

2 Answers2

1

I understand that you are trying to learn the use of 'any' and 'all', but it is not a good idea to remove or delete a term while iterating over a list. This is the cause of the unexpected behaviour of your code. However, you can use a set to get the existing items in a list/tuple without duplicates. For instance:

a = [0,1,3,1,0,3,4,6,4,5]
b = set(a)
print(b)

It returns: set([0,1,3,4,5,6)]

Please notice that the type of b is 'set'. If you want b to be list you can use:

b = list(set(a))
0

If you don't care the order of the sequence, simply do:

list(set(x))
xblymmx
  • 39
  • 2
  • 3