The Python documentation states that, when called with more than one argument, max() returns the largest of the arguments.
>>> a = (1, 1, 1, 9)
>>> b = (4, 5, 6)
>>> max(a, b)
(4, 5, 6)
What defines how large a tuple, in this context, is? The tuple a has both a higher number of elements (four versus three) and its maximum value (9) is greater than the maximum number that can be found in b (6), so by any criteria I would have expected it to be the returned one. How are the tuples being compared by max()?
Tuples like all other sequences are ordered lexicographically: the order of two tuples is decided by the first position where the tuples differ. Quoting from python reference:
Tuples and lists are compared lexicographically using comparison of corresponding elements.
Your two tuples differ on the first position and since 4 > 1, we have
>>> (4, 5, 6) > (1, 1, 1, 9)
True
From left to right it compares each element of the tuples until it finds one larger than the other. This tuple is then returned. For example
>>> a = (2,0,0,0)
>>> b= (1,1,1,1)
>>> max(a,b)
(2, 0, 0, 0)
>>> b = (2,1,1,1)
>>> max(a,b)
(2, 1, 1, 1)
After an element is found in one tuple that is larger than the respective element in the other the remaining values have no effect on which tuple is returned.
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