-1

I'm pretty new to Python and I was trying to figure out a way to delete duplicates from a List. I found other ways to do it, but I would like to know why my way does not work.

numbers = [1, 1, 1, 1]

for number in numbers:

   if numbers.count(number) > 1:
    
      numbers.remove(number)

 print(numbers)

The Output is: [1, 1]

Process finished with exit code 0

It works sometimes, but not all the times.

2 Answers2

2

The remove method only removes the 1st occurrence of the value in the list. Then the loop moves to the next element. You can add print statements like the following to get a picture of what is happening at each iteration in your for loop:

numbers = [1, 1, 1, 1]

for i, number in enumerate(numbers):
    print
    if numbers.count(number) > 1:
        numbers.remove(number)
    print('on loop/index: ', i)
    print('new list after iteration: ', numbers)
print(numbers)

Charles
  • 41
  • 1
0

You could make a new list which contains only the unique values:

numbers = [1, 1, 1, 1]
unique_numbers = list()

for number in numbers:
    if number not in unique_numbers:
        unique_numbers.append(number)
Pieter-Jan
  • 492
  • 4
  • 15