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
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__()
.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With