Python

index() method in tuple

Click for All Topics

index() method in tuple - Python

  • This method is used to find the index position of an element in a tuple.
  • This will return the index position of the first occurrence of an element from a tuple.
  • It will throw a ValueError when the passed element does not exist in the tuple.
  • The time complexity of this method is O(n) where n is the number of elements in the tuple.
  • In this method, you can also specify from where Python can start searching the element and where it has to be searched.

 

Syntax –

tuple.index(element, start, end)

 

Parameters –

  • element → element that’s index position you want to find.
  • start(optional) → starting position from where you want to search, by default its value is 0.
  • end(optional) → end position where you have to search, by default its value is the same as the length of the tuple.

 

Example 1-

				
					my_tuple=(9,99,999,9999,99999,999999)
index_of_99=my_tuple.index(99)
print("Index of 99:",index_of_99)

# Output -
# Index of 99: 1
				
			
  • In the above example, first we create a tuple with some elements and store it in the variable my_tuple.
  • After creating my_tuple, we find the index position of 99 by using the .index() method and store it in the variable index_of_99.
  • Finally, print the index position of 99 on the output screen.

Example 2- find the index of an element using the start and end parameter

				
					my_tuple=('Hello', 'Student', 'this', 'is', 'edSlash')
index_of_is=my_tuple.index('is',1,4)
print("Index Position of 'is' :",index_of_is)

# Output - 
# Index Position of 'is' : 3
				
			

Example 3-find the index of an element that doesn’t exist in the tuple

				
					my_tuple=('a','b','c','d','e','f')
print(my_tuple.index('g'))

# Output -
# Traceback (most recent call last):
  # File "/home/main.py", line 2, in <module>
    # print(my_tuple.index('g'))
# ValueError: tuple.index(x): x not in tuple
				
			

Example 4- find the index value of an element without using any in-built(.index()) method

				
					t=(10,20,30,40,50,60,10,70,20)
for i in range(len(t)):
	if t[i]==70:
		print(i)
		break

# Output -
# 7