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 4My 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 TrueThis 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 FalseCan 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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With