# Beginner : removing tuples from a list

Mike C. Fletcher mcfletch at rogers.com
Sat Feb 8 21:25:31 CET 2003

```Ways to get what you want:

>>> t =
[(1,'john','usa'),(2,'jim','uk',),(3,'jeanne','f'),(4,'jack','usa')]
>>> europe = ['uk','f']
>>> filter( lambda x, europe=europe: x[2] not in europe, t )
[(1, 'john', 'usa'), (4, 'jack', 'usa')]
>>> [ entry   for entry in t    if entry[2] not in europe ]
[(1, 'john', 'usa'), (4, 'jack', 'usa')]
>>> for i in xrange( len(t)-1, -1, -1):
...     if t[i][2] in europe:
...         del t[i]
...
>>> t
[(1, 'john', 'usa'), (4, 'jack', 'usa')]
>>>

The problem you're seeing is that you're mutating the list you're
iterating over so that the for-loop is winding up skipping indices.
Reverse iteration works, as would using a while loop and only
incrementing the index when you _don't_ delete the current item.  The
filter and list-comprehension versions are actually different beasts,
they create entirely new lists, rather than changing the original.

HTH,
Mike

Fabrizio wrote:

>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...
>
>
>
>Fabrizio
>
>
>
>
>
>

--
_______________________________________
Mike C. Fletcher
Designer, VR Plumber, Coder
http://members.rogers.com/mcfletch/

```