Reputation: 408
I have two tuples a = (('1',), ('2',), ('3',),)
and b = (('1',), ('3',),)
. I need to get the result as (('2',),)
since, 2 is the element that is present in a
and not in b
.
I referred this Find intersection of two lists? and Is there a way to get the difference and intersection of tuples or lists in Python? for getting an idea, but these are for lists and not for tuples. I am not able to use intersection() for tuples.
Is there a way I can get a-b
in python tuples?
Upvotes: 2
Views: 1641
Reputation: 7157
Convert to set
then you can get the difference, then convert it back to tuple
using tuple()
function:
a = (('1',), ('2',), ('3',),)
b = (('1',), ('3',),)
result = tuple(set(a) - set(b))
print(result)
Running example: https://repl.it/M1FD/1
If you want the Symmetric Difference, elements in either set but not in the intersection:
set(a) ^ set(b)
or:
set(a).symmetric_difference(set(b))
Running example: https://repl.it/M1FD/2
Upvotes: 3
Reputation: 2084
You can still use sets as described in the linked answer:
In [1]: a = (('1',), ('2',), ('3',),)
In [2]: b = (('1',), ('3',),)
In [3]: set(a).intersection(set(b))
Out[3]: {('1',), ('3',)}
In [4]: set(a).difference(set(b))
Out[4]: {('2',)}
Upvotes: 0
Reputation: 3341
Sets are very useful for this.
If you're only looking for elements that are in a
but not in b
:
set(a) - set(b)
If you're looking for elements that are in either one of the tuples, but not the other:
set(a) ^ set(b)
Upvotes: 1