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?
In the majority of programming languages when you need to access a nested data type (such as arrays, lists, or tuples), you append the brackets to get to the innermost item.
Short answer: To filter a list of lists for a condition on the inner lists, use the list comprehension statement [x for x in list if condition(x)] and replace condition(x) with your filtering condition that returns True to include inner list x , and False otherwise.
The tuple index() method helps us to find the index or occurrence of an element in a tuple. This function basically performs two functions: Giving the first occurrence of an element in the tuple. Raising an exception if the element mentioned is not found in the tuple.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With