why does the statement [1,2] < [2,1] evaluate to True in python
--
Track title: CC B Schuberts Piano Sonata No 16 D
--
Chapters
00:00 Question
00:34 Accepted answer (Score 4)
01:37 Answer 2 (Score 2)
02:02 Thank you
--
Full question
https://stackoverflow.com/questions/4788...
Accepted answer links:
[Comparing Sequences and Other Types]: https://docs.python.org/3/tutorial/datas...
Answer 2 links:
[lexicographically by each element]: https://docs.python.org/2/tutorial/datas...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python
#avk47
ACCEPTED ANSWER
Score 4
The comparison is made item by item in each list:
>>> [1, 2] < [2, 1] # 1 < 2: because the first two items differ, comparison ends here
True
>>> [1, 2] == [1, 2] # 1 == 1 and 2 == 2
True
>>> [1, 2][0] < [2, 1][0] # 1 < 2
True
>>> [1, 2][1] > [2, 1][1] # 2 > 1
True
More about Comparing Sequences and Other Types:
Sequence objects may be compared to other objects with the same sequence type. The comparison uses lexicographical ordering: first the first two items are compared, and if they differ this determines the outcome of the comparison; if they are equal, the next two items are compared, and so on, until either sequence is exhausted. If two items to be compared are themselves sequences of the same type, the lexicographical comparison is carried out recursively. If all items of two sequences compare equal, the sequences are considered equal.
ANSWER 2
Score 2
I'm sure this is a duplicate somewhere, but when you're comparing lists, the comparison is being done lexicographically by each element. Python first compares 1 to 2, the first elements of each list. This is true, so the right list is greater than the left.