when we type [1,4,2]<[1,5]
in python, it returns the value True
.
please explain why this happens?

- 1,048,767
- 296
- 4,058
- 3,343
1 Answers
Python compares lists lexicographically; element by element, until a difference is found.
In your example, the first elements are equal (1 == 1
), but the second elements differ. 4 < 5
is True
, so [1, 4, 2] < [1, 5]
is True
too.
Quoting the Comparisons expressions documenattion:
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 ascmp(x,y)
. If the corresponding element does not exist, the shorter sequence is ordered first (for example,[1,2] < [1,2,3]
).

- 1,048,767
- 296
- 4,058
- 3,343