-2

What is the problem in the below code for "removing duplicates in ~~~list". I know we can use append() to do the same thing.

    l=0
    numbers = [101,3,7,2,3,5,9,11,11,11,9,4,9,81,6]
    numbers.sort()
    for each_element in numbers:
        if each_element==l:
            l = each_element
            numbers.remove(each_element) 
        else:
            l=each_element
    print(numbers)  

~~~ end of code
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
  • It is not a good idea to modify the list while iterating through it. – Gino Mempin May 20 '19 at 04:36
  • Possible duplicate of [while loop with iterator in python which keeps on changing](https://stackoverflow.com/questions/54928236/while-loop-with-iterator-in-python-which-keeps-on-changing) – Devesh Kumar Singh May 20 '19 at 04:37
  • `numbers = sorted(set(numbers))` – Stephen Rauch May 20 '19 at 04:37
  • 2
    Possible duplicate of [How to remove items from a list while iterating?](https://stackoverflow.com/questions/1207406/how-to-remove-items-from-a-list-while-iterating) – DYZ May 20 '19 at 04:37

2 Answers2

0
As pointed by *Gino Mempin* It is not a good idea to modify the list while iterating through it.
Your code logic is correct but that's not how things are happening here.
Understand by this,
let list is [2, 3, 3, 4, 5, 6, 7, 9, 9, 9, 11, 11, 11, 81, 101],
Now when for loop iterates and detects a duplicate at index 2 then '3' at index 2 is removed.
It's what you wanted it to do but problem is that now '4' comes at index 2 from where '3' is removed. But python for loop has already iterated index 2 which means it don't care about whether there has come a new value and it simply iterate from index 3 now knowingly that the list has been modified.
Because of this it's giving you wrong output from your expectation but in actual it's not a python error but in logic according with python/
1UC1F3R616
  • 453
  • 5
  • 10
0

If you use the following castings your list won't contain duplication and it will be sorted.

numbers = sorted(list(set(numbers)))

EDIT:

Complete implementation:

numbers = [101, 3, 7, 2, 3, 5, 9, 11, 11, 11, 9, 4, 9, 81, 6]
sorted_numbers = sorted(list(set(numbers)))
print(sorted_numbers)

Output:

>>> python test.py 
[2, 3, 4, 5, 6, 7, 9, 11, 81, 101]
milanbalazs
  • 4,811
  • 4
  • 23
  • 45