Is there something wrong with my codes?


#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(list):
listn = list
for i in range(0, len(listn)): #外循环从前往后依次取值
for j in range(len(listn)-1, i, -1):
if listn[i] == listn[j]:
del listn[j]
return listn
print remove_duplicates([1, 1, 2, 2, 1, 2, 3, 4])
print remove_duplicates([4, 5, 5, 4])

“”“
Output:
[1, 2, 3, 4]
[4, 5]
Erro Message:
#Your remove_duplicates modifies the list that was passed to it. [4, 5, 5, 4] was modified to [4, 5]. Perhaps you should make a copy first!
”""
What does that message mean? Is there something wrong with my code? Or something wrong with my understand?


#2

To remove duplicate you have a easy method.First conversation that list into set by using set(list) method and again convert the result to list by list(set) method


#3
#return list, returns a list without duplicates.
def remove_duplicates(_list):
    for i in range(0, len(_list)):
            for j in range(len(_list)-1, i, -1):
                if _list[i] == _list[j]: del _list[j]
    return _list
print remove_duplicates([1, 1, 2, 2, 1, 2, 3, 4])
print remove_duplicates([4, 5, 5, 4])

You don’t need to set up a new list inside of the function, you can use the same list.


#4

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