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.
CodePudding user response:
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.
CodePudding user response:
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]