Foundations of Python

122 / 134

Comparison with Tuples

Comparisons work with sequences. So, it works well with the tuples.

Python compares the tuples element-wise starting with the 1st element. If they turn out to be equal, it proceeds to the next one. If it finds any difference in elements, it gives the result without considering the further elements.

print((0, 1, 2) < (0, 3, 4))

It prints True. Can you understand why?

Can you tell what will (0, 1, 2) < (0, 3) return?

It doesn't depend on the number of elements in each tuple. It is only concerned with the two elements that it is comparing at one time.

sort function also works the same way by comparing elements inside each tuple when given a list of tuples.

l = [(0,23,34), (2,34,23), (1,34,23)]
l.sort()

Can you tell the sum of elements in l[2]

If you want to do the sorting in reverse order i.e. from large to small, we can add an argument like this,

l.sort(reverse=True)
Get Hint

Answer is not availble for this assesment


Note - Having trouble with the assessment engine? Follow the steps listed here

Loading comments...