A
A
Anar2018-07-29 04:45:06
Python
Anar, 2018-07-29 04:45:06

Can anyone explain the behavior of a list and the list.remove(x) method in a loop?

Hello! I solved the problem on checkiO, according to the conditions of the problem, a list of numbers (data) is given, you need to return a list of non-unique numbers. It would seem that everything is simple:

def checkio(data: list) -> list:
    for d in data:
        if data.count(d) < 2: #или == 1, поведение не меняется
            data.remove(d)
    return data

But this does not work, for example, for the list [1, 2, 3, 4, 5] the function returns [2,4] (and if you continue, even values ​​are returned), although the list should be empty.
As a result, I decided through .append, but found the following code in the solutions:
result = data.copy()
for n in data:
    if(data.count(n) == 1):
        result.remove(n)
return result

And I didn’t really understand why it works with a copy of the list and does not work with the list itself passed to the function?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question