Beginner : removing tuples from a list

Sean Ross frobozz_electric at hotmail.com
Sat Feb 8 15:46:05 EST 2003


>>> records =
[(1,'john','usa'),(2,'jim','uk',),(3,'jeanne','f'),(4,'jack','usa')]
>>> europe = ('uk','f')
>>> noneuropean = [record for record in records if record[2] not in europe]
>>> noneuropean
[(1, 'john', 'usa'), (4, 'jack', 'usa')]
>>>

or

>>> filter(lambda record: record[2] not in europe, records)
[(1, 'john', 'usa'), (4, 'jack', 'usa')]
>>>

or

>>> noneuropean = []
>>> for record in records:
...  if record[2] not in europe:
...   noneuropean.append(record)
...
>>> noneuropean
[(1, 'john', 'usa'), (4, 'jack', 'usa')]
>>>

hope that helps,
Sean
"Fabrizio" <facelle at libero.it> wrote in message
news:xod1a.96483$YG2.2738784 at twister1.libero.it...
> Hi,
>
> I have a list containing tuples ("records") :
>
> t = [(1,'john','usa'),(2,'jim','uk',),(3,'jeanne','f'),(4,'jack','usa')]
>
> I want to remove all the "european records". I tried the following, but it
> doesn't work  :
>
> europe = ['uk','f']
>
> x = 0
> for z in t :
>     if z[2] in europe :
>         t.pop(x)
>     x = x +1
>
> print t
>
> >>> [(1, 'john', 'usa'), (3, 'jeanne', 'f'), (4, 'jack', 'usa')]
>
> But Jeanne is still there...
>
> TIA for your help
>
>
> Fabrizio
>
>
>
>






More information about the Python-list mailing list