Tuple comparison in Python

comparison, python, tuples

Solution

Your understanding is flawed. It's not `and` - it's a cascading comparison.

a < d or (a == d and b < e) or (a == d and b == e and c < f)

Another way of understanding this for arbitrary length tuples...

def tuple_less_than(tuple1, tuple2):
    for item1, item2 in zip(tuple1, tuple2):
        if item1 != item2:
            return item1 < item2
    return len(tuple1) < len(tuple2)

Problem

According to this : Tuples and lists are compared lexicographically using comparison of corresponding elements. This means that to compare equal, each element must compare equal and the two sequences must be of the same type and have the same length. If not equal, the sequences are ordered the same as their first differing elements. For example, cmp([1,2,x], [1,2,y]) returns the same as cmp(x,y). If the corresponding element does not exist, the shorter sequence is ordered first (for example, [1,2] < [1,2,3]). If I understand correctly ``` (a, b, c) < (d, e, f) ``` gives True if ``` a < d and b < e and c < f ``` why ``` (1, 2, 3) < (2, 0, 4) ``` gives True? how can I do such a comparison?

Original source