On 6/12/2015 4:34 PM, Laura Creighton wrote:
The real problem is removing things from lists when you are iterating
over them, not adding things to the end of lists.

One needs to iterate backwards.

>>> ints = [0, 1, 2, 2, 1, 4, 6, 5, 5]

>>> for i in range(len(ints)-1, -1, -1):
        if ints[i] % 2:
                del ints[i]
        
>>> ints
[0, 2, 2, 4, 6]

But using a list comp and, if necessary, copying the result back into the original list is much easier.

>>> ints = [0, 1, 2, 2, 1, 4, 6, 5, 5]
>>> ints[:] = [i for i in ints if not i % 2]
>>> ints
[0, 2, 2, 4, 6]


--
Terry Jan Reedy

--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to