python - strange result when removing item from a list -
this question has answer here:
- remove items list while iterating 18 answers
i've got piece of code :
numbers = range(1,50) in numbers : if < 20 : print "do something" numbers.remove(i) print numbers
but result i`m getting :
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]
of course i'm expecting numbers below 20 not appear in results, i'm assuming i`m doing wrong remove
you're modifying list while iterate on it. means first time through loop, i == 1
, 1 removed list. for
loop goes second item in list, not 2, 3! that's removed list, , for
loop goes on third item in list, 5. , on. perhaps it's easier visualize so, ^ pointing value of i
:
[1, 2, 3, 4, 5, 6...] ^
that's state of list initially; 1 removed , loop goes second item in list:
[2, 3, 4, 5, 6...] ^ [2, 4, 5, 6...] ^
and on.
there's no way alter list's length while iterating on it. best can this:
numbers = [n n in numbers if n >= 20]
or this, in-place alteration (the thing in parens generator expression, implicitly converted tuple before slice-assignment):
numbers[:] = (n in in numbers if n >= 20)
if want perform operation on n before removing it, 1 trick try this:
for i, n in enumerate(numbers): if n < 20 : print "do something" numbers[i] = none numbers = [n n in numbers if n not none]
wiki
Comments
Post a Comment