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

Jeff Rush jeff at taupro.com
Thu Jul 10 01:44:43 CEST 2008


Anand Chitipothu wrote:
> 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.

Others have explained why it fails.  Here are two approaches for making it 
work, in case you need ideas.

 >>> a = [12, 12, 1321, 34, 23, 12, 34, 45, 77]
 >>> filter(lambda x: x != 12, a)
[1321, 34, 23, 34, 45, 77]

The filter() build-in function is deprecated and the following is the 
preferred way of doing it now:

 >>> [x for x in a if x != 12]
[1321, 34, 23, 34, 45, 77]

Or if your list is quite large and you want to avoid making the new copy of 
it, use the new list generator notation:

 >>> b = (x for x in a if x != 12)
 >>> for x in b:
...     print x
1321
34
23
34
45
77
 >>> list(b)
[1321, 34, 23, 34, 45, 77]

A list generator performs the filtering just-in-time as you need the elements.

-Jeff


More information about the BangPypers mailing list