1

I was writing some code manipulating some lists in python where I ran into this

    #case1
    list1 = [2, 3, 4, 5] 
    list2 = [2, 3, 4, 6]
    #list1 > list2 is False
    
    #case2
    list3 = [1, 2, 3, 10] 
    list4 = [2, 4, 4, 3] 
    #list3 > list4 is also False

From case1 kinda makes sense cause the sum(list1) > sum(list2) but in case2 the sum(list3) > sum(list4) but still list4 is greater than list3. How does python compare two lists?

1

3 Answers 3

1

From the Python documentation:

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.

Sign up to request clarification or add additional context in comments.

Comments

1

list is not compared based on sum. it is compared based on index. in the first case, only 5<6 and others are the same so it returns false. but in 2nd case, 1<2 so it is returning false

this link will help: Comparing two lists using the greater than or less than operator

2 Comments

That means list is compared based on the first different element?
@KritanBhandari yes
-2

Only the first elements of the lists are compared to determine true or false. All the remaining elements can be anything.

1 Comment

This is not accurate. It compares the elements one at a time

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.