Say I have:
t = (('dog', 'Dog'),('cat', 'Cat'),('fish', 'Fish'),
)
And I need to check if a value is in the first bit of the nested tuple (ie. the lowercase bits). How can I do this? The capitalised values do not matter really, I want to search for a string in only the lowercase values.
if 'fish' in t:print "Fish in t."
Doesn't work.
Is there a good way of doing this without doing a for loop with if statements?
The elements of a tuple can be extracted by specifying an index: ('a', 'b')[0] == 'a'
. You can use a list comprehension to iterate over all elements of some iterable. A tuple is also iterable. Lastly, any()
tells whether any element in a given iterable evaluates to True
. Putting all this together:
>>> t = (
... ('dog', 'Dog'),
... ('cat', 'Cat'),
... ('fish', 'Fish'),
... )
>>> def contains(w, t):
... return any(w == e[0] for e in t)
...
>>> contains('fish', t)
True
>>> contains('dish', t)
False