Skip to content
Related Articles
Get the best out of our app
GFG App
Open App
geeksforgeeks
Browser
Continue

Related Articles

Python Tuple – index() Method

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

While working with tuples many times we need to access elements at a certain index but for that, we need to know where exactly is that element, and here comes the use of the index() function. In this article, we will learn about the index() function used for tuples in Python.

Example :

The Index() method returns the first occurrence of the given element from the tuple.

Python3




my_tuple = ( 4, 2, 5, 6, 7, 5)
print(my_tuple.index(5))


Output :

2

Python Tuple Index () Syntax

Syntax: tuple.index(element, start, end)

Parameters:

  • element: The element to be searched.
  • start (Optional): The starting index from where the searching is started
  • end (Optional): The ending index till where the searching is done

Return type: Integer value denoting the index of the element.

Tuple Index() in Python Examples

Find the index of the element

Here we are finding the index of a particular element in a tuple.

Python3




# Creating tuples
Tuple = ( 1, 3, 4, 2, 5, 6 )
   
# getting the index of 3
res = Tuple.index(3)
print('Index of 3 is', res)


Output :

Value of Index of 3 is 1

Get an index from multiple occurrences

Here we are finding the index of a particular element in a tuple with multiple occurrences but here it only returns the first occurrence of that element.

Python3




# Creating tuples
Tuple = ( 3, 3, 5, 7, 3, 3 )
   
# getting the index of 3
res = Tuple.index(3)
print('Index of 3 is', res)


Output:

Index of 3 is 0

Working on the index() With Start and End Parameters

Here we are finding the index of a particular element in a tuple in the given range.

Python3




# alphabets tuple
alphabets = ('G', 'e', 'e', 'k', 's', 'f', 'o',
             'r', 'G', 'e', 'e', 'k', 's')
 
# scans 'G' from index 4 to 10 and
# returns its index
index = alphabets.index('G', 4, 10)
 
print('Index of G in alphabets from index\
                            4 to 10:', index)


Output:

Index of G in alphabets from index 4 to 10: 8

Index of the Element did not Present in the Tuple

Here we are finding the index of a particular element in a tuple that does not exist.

Python3




t = ('G', 'F', 'G')
 
# accessing element not
# present in the tuple
print(t.index('i'))


Output:

Traceback (most recent call last):

  File "08f51264-102d-4f65-b2d3-692a5a750419.py", line 4, in <module>

    print(t.index('i'))

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

My Personal Notes arrow_drop_up
Last Updated : 31 May, 2023
Like Article
Save Article
Similar Reads
Related Tutorials