K
K
kpa6uu2016-03-14 17:02:18
Python
kpa6uu, 2016-03-14 17:02:18

Why is the for loop in Python 3 not behaving as it should?

Hello. The task is to leave only repeating elements in the resulting list.
I tried to implement it as follows, but the for loop behaves rather strangely - it jumps through one index.

def checkio(data):
    for value in data:
 
        if data.count(value) < 2:
 
            data.remove(value)
 
    return data
 
print(checkio([1, 2, 3, 4, 5]))

That is, the values ​​are checked: 1, 3, 5. Two and four somehow magically bypass the check.
If you replace the for loop with while, then everything is OK
def checkio(data):

    i = 0
    while i < len(data):
 
        value = data[i]
 
        if data.count(value) < 2:
 
            data.remove(value)
 
    return data
 
print(checkio([1, 2, 3, 4, 5]))

Please explain why this is happening. How should it be done correctly? Thanks!)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dimonchik, 2016-03-14
@kpa6uu

it's not like in PHP))
it's an iterator, one call - one step,
pushed twice - made two steps
learn the magic of lists:
www.secnetix.de/olli/Python/list_comprehensions.hawk
you can implement, for example:
l = [x for x in l if l.count(x)>1]

E
Eugene 222, 2016-03-14
@mik222

Your code, sorry, stubborn.
You turned the O(N) problem into O(N^2).
Not to mention that you are modifying an iterable array .
Put the values ​​into a hash table. Check for >2 in each iteration and get your solution.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question