[Tutor] search a tuple of tuples

Kent Johnson kent37 at tds.net
Sun Jan 21 19:30:53 CET 2007


johnf wrote:
> Hi,
> I want to find a item within a large tuple that contains tuples.
> mytuple = (('name',123,'value'),('first',345,'newvalue'))
> so a 'for loop' works
> istrue = False
> for i in range(len(mytuple)):
>   if 'first' in mytuple[i]:

This is better written as iteration over mytuple directly, there is no 
need for the index:
for t in mytuple:
   if 'first' in t:
>       istrue = True
>       break
> if istrue:
>   print " true"
> 
> Is possible to use a generator or list comp.  All I want to know is it True or 
> False that mytuple contains 'first'.

Use any() in Python 2.5:

In [1]: mytuple = (('name',123,'value'),('first',345,'newvalue'))

In [2]: help(any)
Help on built-in function any in module __builtin__:

any(...)
     any(iterable) -> bool

     Return True if bool(x) is True for any x in the iterable.

In [5]: any('first' in x for x in mytuple)
Out[5]: True

In [6]: mytuple = (('name',123,'value'),('last',345,'newvalue'))

In [7]: any('first' in x for x in mytuple)
Out[7]: False

Kent



More information about the Tutor mailing list