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

Prashanth munichlinux at gmail.com
Wed Jul 9 17:55:11 CEST 2008


Hi kushal,

On Wed, Jul 9, 2008 at 8:47 PM, Kushal Das <kushaldas at gmail.com> wrote:
>
>>>> 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]


This is not possible in python because when you remove the a[1] then
whole index changes.



>
> Can any one explain me how the remove works and how it is effecting the for
> loop.
>

probably you can do like this

In [18]: import copy

In [19]: a = [12, 12, 1321, 34, 23, 12, 34, 45, 77]

In [20]: templist = cop

In [20]: templist = copy.copy(a)

In [21]: for index in templist:
   ....:     a.remove(index)
   ....:
   ....:

In [22]: a
Out[22]: []



-- 
regards,

Prashanth
http://munichlinux.blogspot.com


More information about the BangPypers mailing list