Reputation: 411
I have recently started studying python programming language and in the process come across the following statement :
[1,2] < [2,1] evaluating to True
I seem not to figure out how the comparison is being done internally by python.
Upvotes: 4
Views: 123
Reputation: 2622
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.
Upvotes: 4
Reputation: 60014
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.
Upvotes: 2