Beginner Level
Intermediate Level
Advanced Level
Introduction
Python is a popular programming language that offers a wide range of functionalities. One of these functionalities is the ability to find the index of an element in a list. We will explore the built-in functions to find the index of a list. This tutorial is designed for beginners who have some knowledge of Python programming and want to learn how to find the index of an element in a list.
Index of a list element :
- Sometimes we need to get the index of a list element to use in our code.
- We can get the index of an element of a list by using the
index()
method. - The syntax of using the index() method is as follows :
index = list_name.index(list_item)
- The lists have zero based index i.e. the index of the first element is zero.
- If we try to find index of an element that is not in the list then we get an error.
- To avoid such situations, it is advised that we make use of in operator before using the
index()
function. - the in operator can be used to check if an element is in the list or not.
- Code Sample :
def find_index(item):
if item in my_list:
index = my_list.index(item)
print(f"Item {item} is at index {index}")
else:
print(f"Item {item} is not in my_list")
my_list = [1, 2, 3, 4]
find_index(3)
find_index(5)
# Output
# Item 3 is at index 2
# Item 5 is not in my_list
- In the code above we have created a function named
find_index()
to find the index of the element of the list. - The element is passed as an argument to the function.
- The function uses the
index()
function to find the index of the element. - If the element is not in the list the
find_index()
function prints a message.
Prev. Tutorial : Iterating a list
Next Tutorial : Sorting a list