14. remove_duplicates


#1

Write a function remove_duplicates that takes in a list and removes elements of the list that are the same.

For example: remove_duplicates([1,1,2,2])
should return [1,2].

Don't remove every occurrence, since you need to keep a single occurrence of a number.
The order in which you present your output does not matter. So returning [1,2,3] is the same as returning [3,1,2].
Do not modify the list you take as input! Instead, return a new list.

def remove_duplicates(x):
result = []
i=0
for i in range(len(x)):
n = i+1
k=0
for n in range(len(x)):
if x[i] == x[n]:
k+=1
n+=1
if k == 0 or i==len(x)-1:
result.append(x[i])
i+=1
return result

Oops, try again. remove_duplicates([4, 5, 5, 4]) returned [4] instead of [4, 5]

I don't know why this cannot be processed! I repeatedly calculated this on hand but.. please


#2

You've got a running variable that is overwritten in the for loop that follows.


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.