T
Thomas Philips
In the past, when deleting items from a list, I looped through the
list in reverse to avoid accidentally deleting items I wanted to keep.
I tried something different today, and, to my surprise, was able to
delete items correctly, regardless of the direction in which I looped,
in both Python 3.2.2. and 2..1 - does the remove() function somehow
allow the iteration to continue correctly even when items are removed
from the midde of the list?
x.remove(i)
x.remove(i)
x.remove(i)
[1, 3, 5, 7, 9]
Sincerely
Thomas Philips
list in reverse to avoid accidentally deleting items I wanted to keep.
I tried something different today, and, to my surprise, was able to
delete items correctly, regardless of the direction in which I looped,
in both Python 3.2.2. and 2..1 - does the remove() function somehow
allow the iteration to continue correctly even when items are removed
from the midde of the list?
if i % 2 == 0:x = list(range(10))
x [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
for i in x:
x.remove(i)
if i % 2 == 0:x [1, 3, 5, 7, 9]
for i in reversed(x):
x.remove(i)
if i % 2 == 0:x [1, 3, 5, 7, 9]
x = list(range(10))
for i in reversed(x):
x.remove(i)
[1, 3, 5, 7, 9]
Sincerely
Thomas Philips