Paulo - 8 months ago 89

Python Question

I have been reading the Core Python programming book and the author shows an example like:

`(4,5) < (3,5) # Equals false`

So I'm wondering, how/why does it equal false? How does python compare these two tuples?

Btw, it's not explained in the book.

Answer

Tuples are compared position by position: the first item of first tuple is compared to the first item of the second tuple; if they are not equal, this is the result of the comparison, else the second item is considered, then the third and so on.

See doc:

Sequence types also support comparisons. In particular, tuples and lists are compared lexicographically by comparing corresponding elements. This means that to compare equal, every element must compare equal and the two sequences must be of the same type and have the same length.

Also 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 considered smaller (for example, [1,2] < [1,2,3] returns True).

**Note** that `<`

and `>`

do not mean "smaller then" and "greater then" but "is before" and "is after": so (0, 1) "is before" (1, 0).

**Note 2**: tuples are not coordinates in a *n-dimensional* space!