How to Use index() Method in Python

How to Use index() Method in Python

5 mins read241 Views Comment
Updated on Mar 30, 2023 16:53 IST

The index method in Python is a powerful tool for finding the position of a specified value in a list. With just a few lines of code, you can quickly and easily search through a list and retrieve the index of a particular value. Learn more about how to use the index method in Python to streamline your code and simplify your programming tasks.

2023_03_MicrosoftTeams-image-245.jpg

In Python, the index() function is used to find the index or position of an element in a list. When there are multiple occurrences of the element in the list, the index() method returns the position of the first occurrence of that element by default.
In this article, we will discuss this function and understand its use with the help of examples. We will be covering the following sections:

Introduction to index() Method in Python

In Python, the index() method is a built-in function that is used to search for an element in a list and returns its position or index. It takes an argument that represents the value or element to search for in the list. If the element is found in the list, index() returns its index, which is the position of the first occurrence of the element. If the element is not found, index() raises a ValueError.

What is Programming What is Python
What is Data Science What is Machine Learning

Syntax of index()

The syntax of index() method in Python is given as follows:

 
list_name.index(element, start, end)
Copy code

Parameters of index()

The list index() method takes the following parameters:

  • element: specifies the element to be searched in the list. It is a mandatory parameter.
  • start and end: specify the starting and ending indices for the search. They are optional parameters.

Return Value of index()

Return Type: int

This function returns the index of an element we have specified for it.

Exceptions of index()

In cases where the element is not found in the list, the index() method raises a ValueError exception. To handle this error, we can use a try-catch block.

Programming Online Courses and Certification Python Online Courses and Certifications
Data Science Online Courses and Certifications Machine Learning Online Courses and Certifications
Recommended online courses

Best-suited Python courses for you

Learn Python with these high-rated online courses

– / –
40 hours
– / –
5 days
– / –
3 days
β‚Ή3 K
3 weeks
– / –
4 days
– / –
20 hours
– / –
2 months
Free
6 weeks
– / –
3 months

Examples of Using the index() Method in Python

Example 1: Finding the index of a substring in a string

 
sentence = "The quick brown fox jumps over the lazy dog"
word = "fox"
start_index = sentence.index(word)
print(start_index)
Copy code

Output:

16

In this example, we have a string that contains the sentence, β€œThe quick brown fox jumps over the lazy dog.” We use the index() method to find the position of the substring β€œfox” in the sentence. The method returns the index of the first occurrence of β€œfox,” which is 16. The index is then printed to the console.

Example 2: Handling exceptions when the element is not found

 
numbers = [1, 2, 3, 4, 5]
try:
index = numbers.index(6)
except ValueError:
index = -1
print(index)
Copy code

Output:

-1

In this example, we have a list of numbers, and we use the index() method to find the position of the element β€œ6.” However, since β€œ6” is not present in the list, the index() method raises a ValueError exception. We use a try-except block to catch this exception and assign a value of -1 to the index variable. This value is then printed to the console.

Example 3: Finding the index of the maximum element in a list

 
numbers = [10, 20, 5, 30, 15]
max_index = numbers.index(max(numbers))
print(max_index)
Copy code

Output:

3

In this example, we have a list of numbers, and we use the max() function to find the maximum element in the list, which is 30. We then use the index() method to find the position of this maximum element in the list. The method returns the index of the first occurrence of β€œ30,” which is 3. The index is then printed to the console.

Example 4: Finding the index of an item in a nested list

 
nested_list = [[1, 2], [3, 4], [5, 6]]
item = 4
for i in range(len(nested_list)):
try:
index = nested_list[i].index(item)
print(f"The index of {item} in the list is ({i}, {index})")
break
except ValueError:
pass
Copy code

Output:

The index of 4 in the list is (1, 1)

In this example, we have a nested list of numbers, and we want to find the position of the element β€œ4” in the list. Since the list is nested, we use a for loop to iterate over each sub-list and use the index() method to search for the element. We use a try-except block to catch the ValueError exception when the element is not found in a sub-list. Once we find the element, we print the index of the element along with its position in the nested list. In this case, element β€œ4” is found in the sub-list at position (1, 1), which corresponds to the second sub-list and the second element in that sub-list.

Conclusion

In practice, the index() method can be used in a variety of applications such as searching for specific items in a shopping list, finding the index of a keyword in a text document, or locating a specific file in a directory. Knowing how to use this method effectively can make your code more efficient and improve your overall programming skills.

FAQs

What happens if the element is not present in the list?

If the element is not present in the list, the index() method raises a ValueError exception.

Can we use the index() method on a tuple?

Yes, you can use the index() method on a tuple to find the position of an element.

How do I find the index of the last occurrence of an element in a list?

You can use the rindex() method instead of index() to find the position of the last occurrence of an element in a list.

Can we use the index() method to find multiple occurrences of an element in a list?

Yes, you can use a loop and the index() method to find all occurrences of an element in a list.

What is the time complexity of the index() method in Python?

The time complexity of the index() method in Python is O(n), where n is the length of the list.

Can we specify a range to search for an element in a list using the index() method?

Yes, you can specify a range by using the optional start and end parameters in the index() method.

How do I handle the ValueError exception when the element is not present in the list?

You can use a try-except block to catch the ValueError exception and handle it accordingly, such as by setting a default value for the index variable.

About the Author

This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio