Select value from list of tuples where condition

I have a list of tuples. Every tuple has 5 elements (corresponding to 5 database columns) and I'd like to make a query

select attribute1 from mylist where attribute2 = something

e.g.

personAge = select age from mylist where person_id = 10

Is it possible to query the list of tuples in some way?


If you have named tuples you can do this:

results = [t.age for t in mylist if t.person_id == 10]

Otherwise use indexes:

results = [t[1] for t in mylist if t[0] == 10]

Or use tuple unpacking as per Nate's answer. Note that you don't have to give a meaningful name to every item you unpack. You can do (person_id, age, _, _, _, _) to unpack a six item tuple.


One solution to this would be a list comprehension, with pattern matching inside your tuple:

>>> mylist = [(25,7),(26,9),(55,10)]
>>> [age for (age,person_id) in mylist if person_id == 10]
[55]

Another way would be using map and filter:

>>> map( lambda (age,_): age, filter( lambda (_,person_id): person_id == 10, mylist) )
[55]

Yes, you can use filter if you know at which position in the tuple the desired column resides. If the case is that the id is the first element of the tuple then you can filter the list like so:

filter(lambda t: t[0]==10, mylist)

This will return the list of corresponding tuples. If you want the age, just pick the element you want. Instead of filter you could also use list comprehension and pick the element in the first go. You could even unpack it right away (if there is only one result):

[age] = [t[1] for t in mylist if t[0]==10]

But I would strongly recommend to use dictionaries or named tuples for this purpose.


Building on Nate's answer: If your list has tuples with non-unique values, this might produce a boolean ValueError (truth value of a Series is ambiguous). To circument that:

mylist = [(25,7),(26,9),(55,10)]
[age for (age,person_id) in mylist if any(person_id == 10)]

Obivously for a "person_id" this less intuitive, but imagine you switch the query: finding all person_IDs for people of a given age.