If it is required to find the cumulative column product of a nested tuple, the 'zip' method and a nested generator expression can be used.
Generator is a simple way of creating iterators. It automatically implements a class with '__iter__()' and '__next__()' methods and keeps track of the internal states, as well as raises 'StopIteration' exception when no values are present that could be returned.
The zip method takes iterables, aggregates them into a tuple, and returns it as the result.
Below is a demonstration of the same −
Example
tuple_1 = ((11, 23), (41, 25), (22, 19)) tuple_2 = ((60, 73), (31, 91), (14, 14)) print("The first tuple is : ") print(tuple_1) print("The second tuple is : ") print(tuple_2) my_result = tuple(tuple(a * b for a, b in zip(tup_1, tup_2)) for tup_1, tup_2 in zip(tuple_1, tuple_2)) print("The tuple after product is : " ) print(my_result)
Output
The first tuple is : ((11, 23), (41, 25), (22, 19)) The second tuple is : ((60, 73), (31, 91), (14, 14)) The tuple after product is : ((660, 1679), (1271, 2275), (308, 266))
Explanation
- Two tuple of tuples (or nested tuples) are defined, and they are displayed on the console.
- The two tuples are zipped, and iterated over, and the respective values are multiplied.
- This is then converted to a tuple, which is assigned to a variable.
- This variable is displayed as the output on the console.