In this article we will discuss different ways to check if an element exists in tuple or not. If yes then also find its index and occurrence count.

Find an element in tuple by value using ‘in’ & ‘not in’

Python provides operator in and not in to check if an element exists in tuple.

Suppose we have a tuple,

Let’s check if element with value 34 exists in tuple using in operator,

As 34 exists in tuple, so output will be,

Now let’s check if an element with value 1001 does not exists in tuple using not in operator,

As 1001 does not exists in tuple, so output will be,

Find the index of an element in tuple using index()

Sometimes just checking if an element exists in tuple is not sufficient, we want to find it’s position of first occurrence in tuple. Tuple provides a member function index() i.e.

It returns the index for first occurrence of x in the tuple. Also, if element is not found in tuple then it will throw an exception ValueError.
Check out these examples,
Example 1:

As 34 exists in the tuple therefore output will be,

Example 2:

As 24 does not exists in the tuple therefore output will be,

Find the occurrence count of an element in the tuple using count()

Tuple provides an another member function count() i.e.

It returns the number of times elem appears in tuple.

Let’s find the occurrence count if element 34 in tuple i.e.

As 34 exists in tuple multiple times, so output will be,

Based on occurrence count we can also check if element exists in tuple i.e.

Output:

Complete example is as follows,

Output:

 

Click Here to Subscribe for more Articles / Tutorials like this.