Search code examples
pythonlistcomparison

How can i get the source implement of List.__gt__() func


I am a new Python programer, my code as below, i am confused why i got result of true. It seems to call the built-in function of __gt__ of List. I don't know where can i get the souce code of the inner(built-in) function of List.gt().

L1 = ['abc', ['123', '456']]
L2 = ['1', '2', '3']
print(L1 > L2)

I will appericate it so much if anyone give an answer.


Solution

  • The behaviour is well specified in the documentation and so you don't really need to read the source code to understand it (but do see my comments at the end of this answer):

    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. If one sequence is an initial sub-sequence of the other, the shorter sequence is the smaller (lesser) one.

    https://docs.python.org/3/tutorial/datastructures.html#comparing-sequences-and-other-types

    It is worth noting that Python 3 no longer allows comparing arbitrary pairs of objects (which was the case in Python 2). This can be illustrated by modifying your example slightly:

    >>> L1 = ['1', ['123', '456']]
    >>> L2 = ['1', '2', '3']
    >>> print(L1 > L2)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: unorderable types: list() > str()
    

    But, if having read all this, you still wish to read the CPython source code, it's available at https://github.com/python/cpython

    In particular, the list comparison code can be found at https://github.com/python/cpython/blob/master/Objects/listobject.c#L2634