-1

hi everyone this is my code to remove repeated items in a list of numbers:

numbers=[5,2,2,2,2,2,34,5,46,78,65,34,78,34,3,2,47,5,8,76]
for item in numbers:
        if numbers.count(item)>1:
                 numbers.remove(item)
print(numbers)

and the result is this: [2, 2, 46, 65, 78, 34, 3, 2, 47, 5, 8, 76]

still has repeated items. but if i change the code in this way: for item in numbers[ : ] it would work and the result is: [46, 65, 78, 34, 3, 2, 47, 5, 8, 76]

what s the difference?
saj
  • 11
  • 1
  • In your loop you're modifying a list which you are iterating over (bad). `a[:]` causes a list to be copied into a new object. – MYousefi Oct 27 '22 at 16:36
  • When the iteration gets to index two and you decide to remove that item, *in* the list what **was** at index 3 is **now** at index two; the iteration continues with the next index (3) which has the item that *used-to-be* at index four - an item got skipped and is never processed. Using a copy for iteration prevents that. – wwii Oct 27 '22 at 17:03

1 Answers1

0

Don't remove items from a list while you're iterating it! That's very dangerous and can return weird results, as you can see. Instead, you can use this approach:

c = set()
unique_numbers = []
for n in numbers:
    if n not in c:
        unique_numbers.append(n)
        c.add(n)

Here is the result:

>>> unique_numbers
[5, 2, 34, 46, 78, 65, 3, 47, 8, 76]

If the order of the numbers does not matter then you can use this approach:

unique_numbers = list(set(numbers))
Riccardo Bucco
  • 13,980
  • 4
  • 22
  • 50
  • thank you for your answer. of coures this is the corrrect way to do that. but i d like to know how it was executed in that way. – saj Oct 27 '22 at 16:50