Function to remove elements from a list not working (corrected)

Maric Michaud maric at aristote.info
Mon Jun 12 06:37:02 EDT 2006


Le Lundi 12 Juin 2006 11:06, Girish Sahani a écrit :
> Thanks!It worked....i wasted a lot of time trying to find a bug in my
> code...what is wrong in iterating over a list and modifying it?
> Doesnt python take the modified list every time the loop starts?

Python iterates over an iterator, that means calling it.next() method at each 
step. Is the iteration is consistent or not when you modify your iterable  
depends on the implementation of the iterator, but in general case it's a bad 
idea, and absolutely error prone.

> Also in this case, i want to add a condition that if none of the pairs are
> in pairList, element = []. How can i do that?
element ?

I guess it's already the case with lst = [ e for e in lst if e in pairs ]


In [1]: lst = (1,2,3,4)

In [2]: pairs=(5,)

In [3]: lst=[e for e in lst if e in pairs]

In [4]: lst
Out[4]: []



-- 
_____________

Maric Michaud
_____________

Aristote - www.aristote.info
3 place des tapis
69004 Lyon
Tel: +33 426 880 097



More information about the Python-list mailing list