[BangPypers] How for and list.remove() works

Anand Chitipothu anandology at gmail.com
Wed Jul 9 17:56:09 CEST 2008


On Wed, Jul 9, 2008 at 8:47 PM, Kushal Das <kushaldas at gmail.com> wrote:
> Hi all,
>
>>>> a = [12, 12, 1321, 34, 23, 12, 34, 45, 77]
>>>> for x in a:
> ...   if x == 12:
> ...     a.remove(x)
>>>> a
> [1321, 34, 23, 12, 34, 45, 77]
>
> Can any one explain me how the remove works and how it is effecting the for
> loop.


put a print and you will understand what is happening.

a = [12, 12, 1321, 34, 23, 12, 34, 45, 77]
print a
for x in a:
    print x, a.index(12)
    if x == 12:
        a.remove(x)

print a

---

[12, 12, 1321, 34, 23, 12, 34, 45, 77]
12 0
1321 0
34 0
23 0
12 0
45 3
77 3
[1321, 34, 23, 12, 34, 45, 77]

It never iterated over the second the 12. When x=12 for the last time,
there was still a 12 at the begining of the list. (try printing the
list also for every iteration).

It internally maintains an index for iteration. If you have a list
with values [x, y, z] and if you remove x in the first iteration, the
list becomes  [y, z]. In the next iteration it returns the second
element, which is z. so y never  gets a chance to be part of the
iteration.


More information about the BangPypers mailing list