2

I am aware of the following:

  • [1,2,3]<[1,2,4] is True because Python does an element-wise comparison from left to right and 3 < 4
  • [1,2,3]<[1,3,4] is True because 2 < 3 so Python never even bothers to compare 3 and 4

My question is how does Python's behavior change when I compare two lists of unequal length?

  • [1,2,3]<[1,2,3,0] is True
  • [1,2,3]<[1,2,3,4] is True

This led me to believe that the longer list is always greater than the shorter list. But then:

  • [1,2,3]<[0,0,0,0] is False

Can someone please explain how these comparisons are being done by Python?

My hunch is that element-wise comparisons are first attempted and only if the first n elements are the same in both lists (where n is the number of elements in the shorter list) does Python consider the longer list to be greater. If someone could kindly confirm this or shed some light on the reason for this behavior, I'd be grateful.

  • 1
    It compares them element-wise until one of them runs out, and if they're the same up that point, the shorter one is first. That is normal [lexicographic ordering](https://en.wikipedia.org/wiki/Lexicographical_order). – khelwood Jun 16 '20 at 10:23
  • 1
    This is explained here https://docs.python.org/3/tutorial/datastructures.html#comparing-sequences-and-other-types – yatu Jun 16 '20 at 10:29

1 Answers1

1

The standard comparisons (<, <=, >, >=, ==, !=, in , not in ) work exactly the same among lists, tuples and strings.

The lists are compared element by element.

If they are of variable length, it happens till the last element of the shorter list

If they are same from start to the length of the smaller one, the length is compared i.e. shorter is smaller

Kuldeep Singh Sidhu
  • 3,748
  • 2
  • 12
  • 22