-2
listnum = [1, 2, 5, 4, 5]

b = len(listnum)

for i in listnum:
    for x in range(b):
        if listnum[x] == i:
            if listnum.index(i) != x:
                listnum = listnum.remove(listnum[x])

above code is a silly approach to a easy task but if I want to make it success I need to remove the subscript error in line 5.

I modified a little like below:

listnum = [1, 2, 5, 4, 5]

b = len(listnum)

for i in listnum:
    for x in range(b):
        if listnum[x] == i:
            if listnum.index(i) != x:
                listnum.remove(listnum[x])
                print (listnum)

but I am getting following output with error:

[1, 2, 4, 5] <-- duplicate values removed :D

Traceback (most recent call last):
  File "d:\pypro\duplicatev.py", line 5, in <module>
    if listnum[x] == i:
IndexError: list index out of range





I got it resolved by some silly inputs also its a specific use case so it will not work for any list, but only for the given list. :P

listnum = [1, 2, 5, 4, 5]

b = len(listnum)

for i in listnum:

    for x in range(b):

        if listnum[x] == i:

            if listnum.index(i) != x:

                listnum.remove(listnum[x])

                print (listnum)

                b = b -1
Anuk
  • 1
  • 2
  • this code doesn't really make a lot of sense... when would `listnum[x] == i` and `listnum.index(i) != x`? – juanpa.arrivillaga May 22 '21 at 20:27
  • it is under for loop so, the index of list should get matched to the nested loop with values of x. – Anuk May 22 '21 at 20:39
  • Please read about [How to debug small programs](http://ericlippert.com/2014/03/05/how-to-debug-small-programs/). You can also use [Python-Tutor](http://www.pythontutor.com/visualize.html#mode=edit) which helps to visualize the execution of the code step-by-step. – Tomerikoo May 22 '21 at 21:16

2 Answers2

1

You can do this using sets, which don't allow duplicates, and if there are duplicates, removes them. Code:

listnum = [1, 2, 5, 4, 5]
listnum = list(set(listnum))

If you want to use your approach, this code should work:

listnum = [1, 2, 5, 4, 5]
for index, item in enumerate(listnum): 
    if listnum.count(item) > 1:
        for _ in range(listnum.count(item)-1):
            listnum.remove(item)
KetZoomer
  • 2,701
  • 3
  • 15
  • 43
  • 2
    You might want to clarify that sets remove duplicates automatically :). – Have a nice day May 22 '21 at 20:30
  • if listnum.count(item) > 1: AttributeError: 'NoneType' object has no attribute 'count' – Anuk May 22 '21 at 20:42
  • Thanks bro!!! cheers, i didn't knew about enumerate function., I got the same result in my code also but its silly :P I know, but satisfying for today. thank you so much for your time n help. – Anuk May 22 '21 at 21:47
-1
setnum = set(listnum)
listnum = list(setnum)
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
SEOKAMELA
  • 1
  • 3