Find an element in Python Tuple by value

Hello programmers, in this tutorial, we will learn how to Find an element in Python Tuple by value.

1. Index() method

The index () method returns the index number of 1st element in the tuple.

Coding

  • 1st we will create a tuple of length 5
  • Then we just use the index() method
  • If the element is present in that tuple, then the index() method returns the index of 1st element for which we are searching.
  • If it is not present in the tuple, then we will get an error which means the item is not persent.
    #tuple
    t=(1,2,'a','b',2)
    print(t)
    #index() method
    print("item peresent at index: ",t.index(2))

output:

(1, 2, 'a', 'b', 2)
item peresent at index:  1

Using for loop: Find an element in a Tuple by value

  • 1st we will create a tuple t, and then we create a variable count and index and set them equal to zero.
  • Then we run a for loop, and inside it, we use a conditional statement that checks if that particular word is present in the tuple and returns how many times an element is present and the index of that element.
count=0
index=0
for i in t:
    if i==2:
        count+=1
        print("element persent at index: ",index) 
    index+=1

output:

element persent at index:  1
element persent at index:  4

Hopefully, you have learned how to find an element in Python Tuple by value.

Also read: Convert tuples into list in Python

Leave a Reply

Your email address will not be published.