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

Boris Borcic bborcic at gmail.com
Mon Jun 12 09:41:34 EDT 2006


Girish Sahani wrote:
> Hi,
>  I am trying to modify a list of pairs (l4) by removing those
> pairs which are not present in a third list called pairList.
>  The following is a simplified part of the routine i have written. However
> it does not give the correct output. Please help!
>  Its possible i have made a trivial mistke since i am a newbie.
> 
> def getl5():
>     l5 = []
>     pairList = [[1,2],[3,4],[3,5],[3,6],[9,7],[8,9],[8,7],[7,9],[11,10]]
>     l4 = [[4,2],[4,7],[4,10],[4,12],[9,2],[9,7],[9,10],[9,12],[11,2],[11,7]]
>     for pair in l4:
>         if pair not in pairList:
>             l4.remove(pair)
>     print "l4 is",l4
> 
> The output given is:
> l4 is [[4, 7], [4, 12], [9, 7], [9, 12], [11, 7]]

use sets

def gets5() :
     pairSet = set([(1,2),(3,4),(3,5),(3,6),(9,7),(8,9),(8,7),(7,9),(11,10)])
     s4= set([(4,2),(4,7),(4,10),(4,12),(9,2),(9,7),(9,10),(9,12),(11,2),(11,7)])
     s4 &= pairSet
     print "s4 is",s4

the output is

s4 is set([(9, 7)])



More information about the Python-list mailing list