fbpx

In this Article , we will discuss about inbuilt python tuple methods which is ‘index()’ and ‘count()’.

Finding all python tuple methods

Create a tuple in notebook and just write the tuple name with a dot and press tab . You will notice all inbuild python tuple methods appears .

python tuple index

index() is an inbuilt python tuple method to find index of any element of tuple . Above we created tuple having 4 numbers . If you have to find index for any of the tuple element ,you need to pass that element as argument to get the index.


python tuple programs for practice:
myTuple.index(4)   #Output =0
myTuple.index(5)   #Output =1
myTuple.index(23)  #Output =2
myTuple.index(6)   #Output =3

Let’s try to pass an argument which is not an element of the tuple say any random number 20 . You will hit ValueError ,that is the 20 is not in tuple .

python tuple programs for practice:
myTuple.index(20)
Output -
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[13], line 1
----> 1 myTuple.index(20)

ValueError: tuple.index(x): x not in tuple

python tuple count

count() is an inbuilt python tuple method to find how many times any element of tuple occurred in that tuple . If you have to find count for any of the tuple element ,you need to pass that element as argument to get the count . In above created tuple 4,5,23,6 all 4 numbers just occurred once . So , output will be 1 only .

python tuple programs for practice:
myTuple.count(4)  #Output=1 

#Let's create a new tuple 'newTuple' where 4 appeared twice 
newTuple=(4,5,23,6,4)

#Now as 4 occured twice in tuple so, output will be 2 here . 
myTuple.count(4)  #Output=2 

Let’s try to pass an argument which is not in the tuple and see what we get. Index was giving error but count will return 0 as if a number is not in the tuple that means count is 0 .

python tuple programs for practice:
myTuple.count(100)  #Output=0

If you have any doubt please comment below or Contact us and we will be happy to help .

To learn Python check out this .

Check out our courses :here

By tecksed

Leave a Reply

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

×