The index() function in python helps to return the index of the given element in the tuple. We can also provide starting and ending point of the search through the tuple.
tuple.index(element, start, end) #where the element may be string, number, list, etc
The index() method takes three parameters. The output of this method should be an integer value indicating the position of the element.
Parameter | Description | Required / Optional |
---|---|---|
element | the element to be searched | Required |
start | start searching from this index | optional |
end | search the element up to this index | optional |
If the method found more than one matching of the given element, it will return only the index of the first occurrence.
Input | Return Value |
---|---|
element | index of element |
if no element | ValueError exception |
# alphabet tuple
alphabet = ('a', 'b', 'c', 'e', 'd', 'e', 'f')
# index of 'c' in alphabet
indexpos = alphabet.index('c')
print('The index of c:', indexpos)
# element 'e' is searched
# index of the first 'e' is returned
indexpos = alphabet.index('e')
print('The index of e:', indexpos)
Output:
The index of c: 2 The index of e: 3
# alphabet tuple
alphabet = ('a', 'b', 'c', 'd', 'e', 'f')
# index of 'g' in alphabet
indexpos = alphabet.index('g')
print('The index of g:', indexpos)
Output:
ValueError: alphabet.index('g'): g not in tuple