Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Python compare two lists of unequal length? [duplicate]

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.

like image 445
Narin Dhatwalia Avatar asked Feb 04 '26 04:02

Narin Dhatwalia


1 Answers

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

like image 65
Kuldeep Singh Sidhu Avatar answered Feb 06 '26 16:02

Kuldeep Singh Sidhu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!