Logical error while removing repeated items from a list

Asked

Viewed 39 times

2

I am doing an exercise where I must create a function that removes repeated items from a list and returns this ordered list.

My code removes only a few repeated items, but leaves others. I know there are other solutions without the use of del, but I’m curious about what I’m missing here, I also accept tips that don’t involve the workout solution.

Follows the code:

def remove_repetidos(lista):

    for itens in lista:
        if lista.count(itens) == 1:
            continue
        lista.remove(itens)

    return sorted(lista)

In case I put [7,3,33,12,3,3,3,7,12,100] as parameter it returns [3, 3, 3, 7, 12, 33, 100].

1 answer

5

The problem is that your code modifies the list within the for in. You can see this by placing a print inside the loop.

>>> lista = [7,3,33,12,3,3,3,7,12,100]
>>> for itens in lista:
...     print(itens)
...     if lista.count(itens) == 1:
...         continue
...     lista.remove(itens)
... 
7
33
12
3
7
12
100

In theory we should see all the items on the console, but that’s not what happens.

Instead of using the same list, you can create a new:

>>> lista = [7,3,33,12,3,3,3,7,12,100]
>>> nova_lista = []
>>> for item in lista:
...     if not item in nova_lista:
...         nova_lista.append(item)
... 
>>> nova_lista
[7, 3, 33, 12, 100]

Or just use the set python:

>>> sorted(set([7,3,33,12,3,3,3,7,12,100]))
[3, 7, 12, 33, 100]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.