Check if element is present in tuple in Python

PythonServer Side ProgrammingProgramming

When it is required to check if an element is present in the tuple or not, a simple loop can be used. A tuple is an immutable data type. It means, values once defined can't be changed by accessing their index elements. If we try to change the elements, it results in an error. They are important contains since they ensure read-only access.

Below is a demonstration of the same −

Example

Live Demo

my_tuple_1 = (23, 45, 12, 56, 78, 0)

print("The first tuple is : ")
print(my_tuple_1)
N = 12
print("The value of 'N' has been initialized")

my_result = False
for elem in my_tuple_1 :
   if N == elem :
      my_result = True
      break
print("Does the tuple contain the value mentioned ?")
print(my_result)

Output

The first tuple is :
(23, 45, 12, 56, 78, 0)
The value of 'N' has been initialized
Does the tuple contain the value mentioned ?
True

Explanation

  • A tuple is defined, and is displayed on the console.
  • The value of 'N' is initialized.
  • The loop is iterated over, and if the element 'N' is present in the tuple, a value is assigned 'True'.
  • This value is assigned to a result.
  • It is displayed as output on the console.
raja
Published on 11-Mar-2021 14:21:20
Advertisements