0

I am new to python and currently learning the basics.
I want to remove duplicates in a list.
Here is my code:

numbers = [2, 4, 5, 6, 9, 4, 0, 8, 2, 4]
for item in reversed(numbers):
    if numbers.count(item) > 1:
        numbers.remove(item)
print(numbers)

The result I expected is

[2, 4, 5, 6, 9, 0, 8]

However, I got instead

[5, 6, 9, 0, 8, 2, 4]

I don't know why this happened since I use reversed iterator. So any explanation is appreciated.

Crown716
  • 115
  • 10
CharlieH
  • 1
  • 1
  • 2
    ```.remove(item)``` is being called on the first instance of each number of the list, not the last one – 7koFnMiP Nov 02 '21 at 04:19
  • While your mistake is new, the correct solution to this sort of issue is already found on [How do you remove duplicates from a list whilst preserving order?](https://stackoverflow.com/q/480214/364696). – ShadowRanger Nov 02 '21 at 04:39

2 Answers2

0

You can use this method

numbers = [2, 4, 5, 6, 9, 4, 0, 8, 2, 4]

finale = list(dict.fromkeys(numbers))

output:

[2, 4, 5, 6, 9, 0, 8]

As dictionaries cannot contain duplicate keys, the function removes any duplicate values from our list. We can then convert our dictionary back to a list.

xio
  • 630
  • 5
  • 11
0

As pointed out by 7koFnMiP, the remove() method removes the first occurrence of the element with the specified value.

One way to solve this is to use pop() instead of remove(), to have a way to reference the index of the object to be removed from the list.

Here's an example, using an iterator referencing the index backwards to start removing from the end of the list:

numbers = [2, 4, 5, 6, 9, 4, 0, 8, 2, 4]

for item in reversed(numbers):
    if numbers.count(item) > 1:
        # where the difference is:
        numbers.pop(next(i for i in reversed((range(len(numbers)))) if numbers[i] == item))
print(numbers)

The output is as expected:

[2, 4, 5, 6, 9, 0, 8]

More info on the built-in function next()

More info on list comprehensions

Jorge Gx
  • 311
  • 3
  • 13