How to Compare Tuples in Python?

Estimated read time 2 min read

In Python, you can compare tuples using the comparison operators (<, <=, >, >=, ==, !=). Tuples are compared element by element, starting from the first element. If the first elements of the tuples are not equal, the comparison result is determined based on the comparison of the first elements. If the first elements are equal, the comparison moves on to the next elements until a difference is found or all elements have been compared. Here’s an example:

tuple1 = (1, 2, 3)
tuple2 = (1, 2, 4)

result = tuple1 < tuple2



In this example, the comparison is performed between tuple1 and tuple2 using the < operator. The first elements of both tuples are equal, so the comparison moves to the second elements. Since the second element of tuple1 is less than the second element of tuple2, the comparison result is True.

You can use any of the comparison operators (<, <=, >, >=, ==, !=) to compare tuples in a similar manner.

It’s important to note that tuple comparison follows a lexicographical order. If the tuples have different lengths, the comparison will be based on the common elements, and the longer tuple will be considered greater.

By using the comparison operators, you can compare tuples in Python and obtain the comparison result based on the element-wise comparison of the tuples.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply