Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Grammar of tuple comparisons

Went to this question in search for the underlying reason of my mistake, but not sure if I understand why one works and the other doesn’t:

Grammatically, for a dictionary where values are tuples:

my_dict = {'Cierra Vega': (6.2, 70), 'Alden Cantrell': (5.9, 65), 
           'Kierra Gentry': (6.0, 68), 'Pierre Cox': (5.8, 66)}

and we wish to filter for key:value pairs where the (a) the first value in the tuple is value[0]> 6 and (b) the second value in the tuple is value[1] > 70,

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

why does the tuple comparison made to be an element-wise conditional statement succeed

dict(filter(lambda x: (x[1][0], x[1][1]) >= (6, 70), my_dict.items()))
>>>
{'Cierra Vega':(6.2,70)}

but the joint-and comparison fails?

dict(filter(lambda x: ((x[1][0] >= 6) and (x[1][1] >= 70)), my_dict.items()))
>>>
{}

>Solution :

First of all, I am a little confused about "failing" and "succeeding", since no entries of your dictionary actually satisfy your request, so it makes sense that the succeeding case is the latter one, where no results are returned.

And, actually, that makes sense, because tuples are ordered lexicographically, meaning that (a, b) ≥ (c, d) iff a > c or (a == c and b ≥ d). This generalizes to not only couples, but any tuple. So when you are checking for x[1] > (6, 70), it’s not at all equivalent to x[1][0] > 6 and x[1][1] > 70, hence the different results.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading