python

index() function in python

The index() function in python can be used to return the index of an item that exists in a list or the index of a substring that exists in string.

#Get index of substring
my_str = "Hello World"
index_of_str = my_str.index("Wor")
print(index_of_str)
# -> 6

# Get index of an element in a list
my_list = ["James", "Rick", "Carol", "Carl"]
index_of_item = my_list.index("Carol")
print(index_of_item)
# -> 2

Using above code examples, we are using index() function of Python String and Python List. The function is used to get the index of item in list or string.

index() function

The index function takes the value as a parameter that needs to be checked in an array or list and return the very first position index of it. For example if we have a string 'Hello' and we want to get the index of 'l' in this string then the 'Hello'.index('l') function will return 2.

Syntax of index() function

List.index(value, from_index, to_index)

value: The value parameter is a required parameter in index() method. This is the value that needs to be checked in the list or string and the very first index is returned.

from_index: This is an optional parameter where we can pass from which index we want to start the search of given value.

to_index: This is also an optional parameter and this is the last index value where we want to end our search.

my_list = [5, 3, 1, 9, 6, 2, 4, 5, 9, 7]

result = my_list.index(5, 3, 10)
print(result)
# -> 7
Here, we are getting the index of a value 5 in a list named my_list. If we will not pass start and stop index inside the index() function it will return 0. As we are passing start index as 3 and stop index as 10 so it is returning 7.
Was this helpful?