0

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 ?

Community
  • 1
  • 1
caspersky 48
  • 239
  • 1
  • 4
  • 11

3 Answers3

2

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)
[]
Blender
  • 289,723
  • 53
  • 439
  • 496
0

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.

Eric Wilson
  • 57,719
  • 77
  • 200
  • 270
0

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.

Sudipta Chatterjee
  • 4,592
  • 1
  • 27
  • 30