Yannis
Yannis

Reputation: 205

Tuple comparison in Python

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?

Upvotes: 3

Views: 3160

Answers (3)

Amber
Amber

Reputation: 526543

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)

Upvotes: 6

woot
woot

Reputation: 7606

Think of it like comparing 2 strings. The first non-equal comparison of each element determines the comparison result.

(1, 2, 3) < (2, 3)
True

"123" < "23"
True

Upvotes: 0

Jan Vlcinsky
Jan Vlcinsky

Reputation: 44092

Simply explained, read the values as if they are decimal numbers

123 < 204

This is oversimplified, but what I mean, it compare elements one by one, and it ends as soon as the elements are not the same.

Upvotes: 0

Related Questions