If it is required to find the maximum of the similar indices in two list of tuples, the 'zip' method and list comprehension can be used.
The list comprehension is a shorthand to iterate through the list and perform operations on it.
The zip method takes iterables, aggregates them into a tuple, and returns it as the result.
A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on).
A list of tuple basically contains tuples enclosed in a list.
Below is a demonstration of the same −
Example
my_list_1 = [( 67, 45), (34, 56), (99, 123)] my_list_2 = [(10, 56), (45, 0), (100, 12)] print ("The first list is : " ) print(my_list_1) print ("The second list is : " ) print(my_list_2) my_result = [(max(x[0], y[0]), max(x[1], y[1])) for x, y in zip(my_list_1, my_list_2)] print("The maximum value among the two lists is :") print(my_result)
Output
The first list is : [(67, 45), (34, 56), (99, 123)] The second list is : [(10, 56), (45, 0), (100, 12)] The maximum value among the two lists is : [(67, 56), (45, 56), (100, 123)]
Explanation
- The two lists of tuples are defined, and are displayed on the console.
- The 'zip' method is used to combine both the list of tuples, and the 'max' method is used to fetch the maximum value among the tuples.
- This is converted to a list.
- This operation is assigned a variable.
- This variable is the output that is displayed on the console.