Find common elements from two tuples in Python

In this tutorial, we will learn how to find common elements from two tuples in Python. Sometimes while programming there may be a situation when we have t0 find common things between two tuples.

A tuple is a sequence of immutable(constant, which can not be changed)  data or objects, such as the name of an employee, his age, height, gender, and his blood group. Tuple provides the programmer with a hint that the data can not be changed.

If you are not familiar with the use of tuple and don’t know how to find common elements from two tuples in Python then this post is for you. Because in this we are going to find out how to find common elements from two tuples in Python.

Also, read: Get the IP address of a URL in Python

Finding common elements from two tuples in Python

Let’s begin learning with some light examples.

At first, create a variable that will hold the objects or elements of the first tuple.

tpl1=(4,'v',(1,3),9,8,('m','v'))

Then create another variable that will hold elements of the second tuple.

tpl2=(7,6,(3,1),5,9,('m','v'))

In Python, we have a method(function) set() which is the collection of iterable and mutable data types with no duplicate elements. Now we pass both tuples in function set() and store the result in two variables as shown below.

tpl1_set=set(tpl1)
tpl2_set=set(tpl2)

The method set() returns the non-duplicate elements that will be stored in variables tpl1_set and tpl2_set. To find common elements between them we perform AND(&) operation between tpl1_set and tpl2_set which will return those elements which are common in both.

commonElement=(tpl1_set & tpl2_set)
print(commonElement)

Our program will give the output as follow:

{9, ('m', 'v')}

Curly braces show that output is of the set data type. Type conversion can be used to convert the set into tuple again.

commonElement=(tpl1_set & tpl2_set)
print(tuple(commonElement))

Now the output will be as following:

(9, ('m', 'v'))

Thank You.

 

Leave a Reply

Your email address will not be published. Required fields are marked *