Python Program to search an element in a tuple


In Python, searching for elements within a data structure is a common task and different types of data structures should aim to provide efficient methods for searching. The problem of searching involves finding a specific element within a container and returning a value if it is not found.

One data structure that can be used for this task is a tuple, which stores a collection of different types of data in a single variable. These items can be accessed by their index and Python offers various methods to work with them. Tuples are immutable, meaning that once created, they cannot be modified. Any operations performed on a tuple will result in a new tuple with the updated values.

We can define a tuple in python using the round brackets enclosing the data that we wish to store −

var = (1, 'a', 3.7)

Whenever we need to check whether an item exists in a tuple or not, we must look for ways to search for that item in it. Thankfully python provides us with methods to solve this problem for us. Some of the ways with which we can determine whether an element exists in a tuple are listed below.

  • Using the for loop of python

  • Using the in operator of python

  • Using index method of tuple objects

Using the for loop of python

Python provides us with several ways to iterate over a tuple, list etc. By using the loop, we will iterate over all the elements of the tuple. At each iteration, we will check whether the current element is equal to the element we are searching for.

If it matches, we break out of the loop with the element found message and if we go over all the elements and the element is still not found we shall print the not found message

Algorithm

Let’s look at the algorithm for the above method −

Step 1 - Create a tuple

Step 2 – Create a counter variable to track the status of the element found or not

Step 3 – Start iterating over the elements using for loop

Step 4 – Check whether the current value is equal to the value we are searching for using the comparison operator and if statement.

Step 5 – if yes, then we found the element, set found to true, and break out of the loop

Step 6 – if no, then continue to the next element

Step 7 – When program gets out of the loop, check whether the value of counter variable is true or not

Step 8 – if yes, print element found

Step 9 – if no, print element not found

Example

In this example we used for loop to iterate over the list and compare each element with the given number if the element is equal to the given number we break the for loop and print that element is present.

A = (1, 2, 3, 4, 6)
isFound = False
elem = 5
for item in A:
   if item == elem:
      isFound = True
      break
   if isFound:
      print("Element found")
   else:
      print("Element not found")

Output

Element not found
Element not found
Element not found
Element not found
Element not found

Using in Operator

The in operator determines whether a given value is a constituent element of a sequence such as a string, array, list, or tuple.

Python provides an easy solution for the problem of checking the presence of an element in an iterable. That is the “in” operator. It is a built-in method of python that functions in the same way as the approach we discussed above, but it results in Boolean values.

Meaning, if the item we are searching for is present in the iterable, tuple in this case, it will result in true and if the element is absent the expression will result in False. The syntax for using the in operator is as follows −

ElementToSearch in VariableToSearchIn

Example

Following is an example to search an element in an array using the in operator. In here, we used the in operator of python which checks if an element is present in a data structure.

If this operator returns true it means the item is present and we return the element is present. If the operator returns false we return element not found.

array = ("mango", "banana", "apple", "orange")
elem = "mango"
if elem in array:
   print ("Element found")
else:
   print ("Element not found")

Output

Element found

Using index()method of tuple

We can access the elements of a tuple by its index in the following way: tuple_name[index]

As we have already discussed that tuple is a pre-defined class in python, therefore it has several methods available to perform simple tasks. One such method is the index method.

It takes the value to be searched as input and returns the index of the first occurrence of that element as the return value in case the element is not present it raises an exception.

As there is the possibility of exception being through, we will be using the try and except block for error handling.

Example

In the following example we have used the index() function to get the index of the given number if it gives the index we print that element is found else, we print “element is not found”.

input_array = (1, 2, 3, 5, 6, 7)
elem = 4
try:
   A.index(elem)
   print("Element found")
except:
   print("Element not found")

Output

Element not found

Conclusion

In this article we focused on three different ways to search for an element in a tuple. We learnt the use of for loops, using in operator and using the index method of the tuple class.

Updated on: 20-Feb-2023

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements