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)
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.
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)