How can I subtract tuple of tuples from a tuple in Python?


The direct way to subtract tuple of tuples from a tuple in Python is to use loops directly. For example, if

you have a tuple of tuples

Example

((0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11), (12, 13, 14))

and want to subtract (1, 2, 3, 4, 5) from each of the inner tuples, you can do it as follows

my_tuple = ((0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11), (12, 13, 14))
sub = (1, 2, 3, 4, 5)
tuple(tuple(x - sub[i] for x in my_tuple[i]) for i in range(len(my_tuple)))

Output

This will give the output

((-1, 0, 1), (1, 2, 3), (3, 4, 5), (5, 6, 7), (7, 8, 9))

Updated on: 05-Mar-2020

228 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements