Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print difference between two tuples

How can I print just the differences between two tuples?

 >>>a=(1,2,3,4)
 >>>b=(2,3,5,6)

If the tuples are as above then the expected output is (1,4,5,6). The compare functions can only compare but could not find the differences.

The tuples are generated by MySQLdb python library. The queries being executed produces a fair amount of data.

In [13]: c.execute(query)
Out[13]: 86844L
In [14]: qop1 = c.fetchall()
In [19]: len(qop1)
Out[19]: 86844

So if I compare every tuple with custom code it will take a lot of time. Can I achieve this an efficient way like an inbuilt python library?

like image 827
cutteeth Avatar asked Jun 13 '26 05:06

cutteeth


2 Answers

You want the Symmetric Difference -- elements in either set but not in the intersection. This can be done by:

set(a) ^ set(b)

or:

set(a).symmetric_difference(set(b))
like image 52
reece Avatar answered Jun 14 '26 19:06

reece


From your example one can deduce that you are asking about symmetric difference of sets and in python you can simply do

a=(1,2,3,4)
b=(2,3,5,6)
print tuple(set(a) ^ set(b))
like image 32
lejlot Avatar answered Jun 14 '26 20:06

lejlot



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!