0

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)
    new_tuple -> (1,(2,'b'),4)

Thanks.

zeddypop
  • 11
  • 2
  • 3

2 Answers2

0

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

RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
0

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)
user94559
  • 59,196
  • 6
  • 103
  • 103