Skip to content Skip to sidebar Skip to footer

Extract Common Element From 2 Tuples Python

I have 2 tuples A & B. How can I extract the common elements of A & B to form a new tuple? For example: A -> (1,'a',(2,'b'),3,'c',4) B -> (1,(2,'b'),4,8)

Solution 1:

With set intersection (to return a new set with elements common to the set and all others):

A = (1,'a',(2,'b'),3,'c',4)
B = (1,(2,'b'),4,8)
result = tuple(set(A) & set(B))

print(result)

The output:

(1, 4, (2, 'b'))

https://docs.python.org/3/library/stdtypes.html?highlight=set#frozenset.intersection

Solution 2:

You could use set intersection. Note that this doesn't guarantee anything about the order of the elements.

>>>A = (1,'a',(2,'b'),3,'c',4)>>>B = (1,(2,'b'),4,8)>>>tuple(set(A).intersection(set(B)))
(1, (2, 'b'), 4)

Post a Comment for "Extract Common Element From 2 Tuples Python"