Searching through a list of tuples

Peter Hansen peter at engcorp.com
Tue Jul 12 00:40:05 EDT 2005


Repton wrote:
> I often find myself storing data in a list of tuples, and I want to ask
> questions like "what is the index of the first tuple whose 3rd element
> is x", or "give me the first tuple whose 2nd element is y".
> 
> I know I can do [elem for elem in lst if elem[3] == x][0] or (elem for
> elem in lst if elem[2] == y).next() but it feels kinda ugly; is there a
> better way?
> 
> (something like lst.index(x, key=..) or lst.find(y, key=..) would be
> nice)

If the latter form would make you happy, why not just write a simple 
utility function that does what you want (by using the first technique, 
if you wish), and then calling it will be as simple as lst.index(....)

And no, since you are basically doing a form of pattern matching, I 
don't think there's a shortcut.

-Peter



More information about the Python-list mailing list