Home>

I mostly do C/C++ development, but the task of writing an application in Python-3 came up and I ran into some misunderstanding of the interpreter.

I made a mistake and didn't notice it for a while because Python did everything "almost" right. The task was to remove N/2 values ​​from the list, where N is their total number.

A simple example describing the situation:

array= []
for i in range(10):
    array append(i)
# array [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
i= 0
for item in array:
    if i < len(array)/2:
        array.remove(item)
#array [1, 3, 5, 7, 9]

As you can see, I don't increment the variableiin the second loop, but the interpreter somehow still removes zero and every even element from the array.

Actually, how does it work?

I figured it out, it turns out that the shift of the item index is triggered and therefore it jumps.

Culit2022-01-30 14:11:02

Do not delete the question: it will most likely help other people too

VladD2022-01-30 14:11:02

@Culit if you figured it out, it would be nice not to delete the question, but to answer it yourself. May help others in the future. Well, if you don't want to answer yourself, then at least don't delete the questions so that other members can answer (:

Suvitruf - Andrei Apanasik2022-01-30 14:11:02