What is wrong on my code

kindly need anybody assistance to know what is wrong on the below code I write this code to remove all the duplicates numbers on a list but the code remove the duplicates of (1) but does not remove any other duplicates
the code:

list=[1,1,1,2,2,2,6,6,6,6,8,7,9,4]
for item in list:
    if list.count(item)>1:
        list.remove(item)
print(list)

the output:
[1, 2, 2, 6, 6, 8, 7, 9, 4]

Mutating a list while you iterate over it can produce confusing results. In this case, you are deleting list elements, but then everything in the list shifts and your iteration doesn’t work correctly anymore.

1 Like

You should make a copy of the list for iteration and edit the original.

You could created an empty list to store the non-duplicates and while iterating through the list check whether the item is NOT in the new list. If not, then add the item to the new list.

list=[1,1,1,2,2,2,6,6,6,6,8,7,9,4]
list_2 = list() #changing list_2 to a real list
for item in list:
if not item in list_2: #this line of code founds our non duplicated numbers an add them in another list
list_2.append(item)#.append() is a function that only works on lists and basicly adds whatever is in the parentheses to the list
print(list_2)

Seeing the problem has already been solved, Going to post a solution using op’s original code with copy

list_a = [1,1,1,2,2,2,6,6,6,6,8,7,9,4]
list_b = list_a.copy()

for number in list_b:
    if list_a.count(number) > 1:
        list_a.remove(number)

print(list_a)

output
[1, 2, 6, 8, 7, 9, 4]

list=[1,1,1,2,2,2,6,6,6,6,8,7,9,4]
for item in list.copy():
    if list.count(item)>1:
        list.remove(item)
print(list)

Another quick fix which utilizes the exact same logic you used in the original code @1omarayman1. Now the item being iterated over doesn’t change.

Output:

[1, 2, 6, 8, 7, 9, 4]

I would recommend not using list as a variable name, as it is a builtin

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