Possible Duplicate:
Removing from a list while iterating over it
I have this code:
s = [2,3,4,5]
for i in s:
s.remove(i)
print(s)
When I run it, the result is:
[3,5]
What is the logical error here ?
Possible Duplicate:
Removing from a list while iterating over it
I have this code:
s = [2,3,4,5]
for i in s:
s.remove(i)
print(s)
When I run it, the result is:
[3,5]
What is the logical error here ?
You are iterating over the list while modifying it, which is causing your problem.
Make a temporary list (list(s)
) that you iterate over and modify the original to your needs:
>>> s = [2,3,4,5]
>>>
>>> for i in list(s):
... s.remove(i)
...
>>> print(s)
[]
The logical error is in removing elements from a list while iterating through the same list.
Python hides some implementation details, of course. Internally, you remove the first item, leaving [3,4,5]
. Then you remove the second item, leaving [3,5]
. At this point you have removed two items from a list that is only two items long, so you are done.
It is because of the iterator. Consider this code segment:
s = [2,3,4,5]
for i in s:
print "i",i
j = s
print "j", j
s.remove(i)
print "removed"
print "j", j
print "s", s
print s
The output would be
i 2
j [2, 3, 4, 5]
removed
j [3, 4, 5]
s [3, 4, 5]
i 4
j [3, 4, 5]
removed
j [3, 5]
s [3, 5]
[3, 5]
Basically, when you execute the for loop, the the internal iterator goes to s[0], then s[1], etc. When the next round of the loop executes, s[1] is already 4 instead of 3 because s itself has been modified.