0

What happens when we compare list of integers in Python with inequalities?

Does it do an implicit sum()?

>>> [1,1] > [1,1,1]
False
>>> sum([1,1]) > sum([1,1,1])
False
>>> [1,1,1] > [1,1,1]
False
>>> [1,1,1,1] > [1,1,1]
True
>>> sum([1,1,1,1]) > sum([1,1,1])
True

If so, which part of the CPython code does that?

It looks like it's not comparing len():

>>> pos, neg = [1,0], [0,0,0]
>>> pos > neg
True
martineau
  • 119,623
  • 25
  • 170
  • 301
alvas
  • 115,346
  • 109
  • 446
  • 738
  • 1
    List items are compared lexicographically – juanpa.arrivillaga Nov 17 '17 at 01:53
  • @juanpa.arrivillaga Even when they are ints? –  Nov 17 '17 at 01:54
  • What does that mean? They compare the `len()`? – alvas Nov 17 '17 at 01:54
  • 1
    Lexicographic just means "dictionary order"; it has nothing to do with the type of element. Compare the first elements, and if they are equal, move on to the next. – chepner Nov 17 '17 at 01:55
  • I should say, list objects are compared lexicographically on their elements. – juanpa.arrivillaga Nov 17 '17 at 01:56
  • The pair of items at each index are compared in the usual way (e.g. `1 > 1`); types do matter here since comparing uncomparable types will fail as usual (e.g., `'a' >1` will fail). As soon as a non-equal pair is found, the overall result is the result of that comparison (this applies whether the lists are the same length or not). If one of the lists is shorter and is a sub-sequence of the other list (e.g., `[1, 1]` is a sub-sequence of `[1, 1, 1]`) the shorter list will be considered less than the longer list. If two lists are the same length and all items are equal, they're considered equal. –  Nov 17 '17 at 02:23

0 Answers0