How do I compare tuples in Python with examples?

In Python, tuples are compared lexicographically using the comparison operators like <, >, , etc. This means that Python compares the first elements of the tuples, and if they are equal, it moves to the second elements, and so on. Here are a few examples illustrating tuple comparisons:


# Example of tuple comparison in Python

# Defining two tuples
tuple1 = (1, 2, 3)
tuple2 = (1, 2, 4)

# Comparing the tuples
print(tuple1 < tuple2)  # Output: True (because 3 < 4)
print(tuple1 > tuple2)  # Output: False
print(tuple1 == tuple2)   # Output: False

# Comparing tuples of different lengths
tuple3 = (1, 2)
tuple4 = (1, 2, 3)

print(tuple3 < tuple4)  # Output: True (tuple3 is shorter)
    

Python Tuples Compare Tuples Tuple Comparison Lexicographical Comparison