Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the proper to do the difference between two tuple in python [duplicate]

I'm looking for the proper way to do the difference between 2 tuples. For example:

a = (1, 2, 3)
b = (1, 0, 2)

Difference expected

(0, 2, 1)

I know I can iterate on both tuples create a new tuple then do the difference but i'm looking for something more conventional or proper.

like image 509
mel Avatar asked Feb 06 '26 16:02

mel


2 Answers

You may access both indices in same iteration with help of zip built-in. After that you simply feed generator expression to tuple to create new tuple object.

diff = tuple(x-y for x,y in zip(a,b))
like image 153
Łukasz Rogalski Avatar answered Feb 09 '26 04:02

Łukasz Rogalski


from operator import sub
a = (1, 2, 3)
b = (1, 0, 2)
tuple(map(sub, a, b))

(0, 2, 1)

like image 42
Clodion Avatar answered Feb 09 '26 06:02

Clodion



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!