Home > front end >  Grammar of tuple comparisons
Grammar of tuple comparisons

Time:04-10

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,

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()))
>>>
{}

CodePudding user response:

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.

  • Related