In Python, tuples are compared lexicographically (alphabetical order as seen in an English dictionary) by comparing corresponding elements of two tuples.
It means that the first item of the first tuple is compared to the first item of the second tuple; if they are not equal then that’s the result of the comparison. Else the second item is considered, then the third and so on.
1. Rules for comparing tuples
For understanding the tuples comparison, focus on how words are compared and stored in an English dictionary. Here, each letter of the words can be considered an item in the tuple.
- Compare the n-th items of both tuple (starting with the zero-th index) using the == operator. If both are equal, repeat this step with the next item.
- For two unequal items, the item that is “less than” makes the tuple, that contains it, also “less than” the other tuple.
- If all items are equal, both tuples are equal.
- If one tuple runs out of items during step 1, the shorter tuple is “less than” the longer one.
2. Simple comparison
In given example,
tuple2 are compared by:
tuple2– which are equal
tuple2– which are equal
tuple2– which are NOT equal and decide the result of comparison
tuple1 = (1,2,3) tuple2 = (1,2,4) print (tuple1 == tuple2) # False print (tuple1 < tuple2) # True print (tuple1 > tuple2) # False
2. Compare unequal tuples
Python program to show comparison of tuples having an unequal number of items.
tuple1 = (1,2,3) tuple2 = (4,5,6,7) print( tuple1 < tuple2 ) # True
3. All elements of tuple1 are greater than items of tuple2
Two compare two tuples such that all items in tuple1 are greater than tuple2, we need to use all() function and check comparison on items one by one, for corresponding items in both tuples.
tuple1 = (1,2,3) tuple2 = (4,5,6) result = all(x < y for x, y in zip(tuple1, tuple2)) print( result ) # True
4. Compare tuples with heterogeneous items
Tuples comparison for
== equality operator works for heterogeneous items. But
'less than' and
'greater than' operators does not work with different datatypes.
tuple1 = (1, 2, 3) tuple2 = (1, 2, "6") # "3" will be compared to 6 print( tuple1 == tuple2 ) # False
For evaluating less than or greater than, if we know that tuples can contain items of different types, then we need to use
map() function to convert all values both tuples into a single type.
tuple1 = (1,2,3) tuple2 = (4,5,"6") tuple1 = (1, 2, 3) tuple2 = (1, 2, "6") result = tuple(map(int, tuple2)) < tuple1 print (result) # False # TypeError: '<' not supported between instances of 'int' and 'str' print( tuple1 < tuple2 )
Happy Learning !!
Leave a Reply