How to Find Index of Element in List Python?
![Python Course for Beginners With Certification: Mastering the Essentials](https://www.scaler.com/topics/images/rahul_janghu.webp)
How to find index of element in list Python?
In Python, we can find the index of an element in a list using two methods:
- Using the index() method
- Using a for loop
These methods are explained in the following sections.
Method 1: Using the index() Method
The index() function in Python searches for an element in a list and returns its index. If the element occurs more than once in the list, the index of its first occurence is returned and if the element is not present in the list, the function raises a ValueError.
Syntax of the index() Method
The list_name is the list in which we are searching the element.
Parameters of the index() Method
The list index() method has 3 parameters:
- element: The element to be searched in the list.
- start (optional): The index where from the search starts in the list.
- end (optional): The index at where the search ends in the list.
Return values of the index() Method
The list index() method returns the index of the first occurence of the element to be searched in the list.
It raises a ValueError if the element to be searched is not found in the list.
Example 1: To find index of element in list Python
Code
Output
In the above example, we are finding the index of 6 and 12 in using the index() method. The 6 is at the index and 12's first occurrence is at the index in the list.
Example 2: Finding the index when element is not present in the List
Code
Output
In the above example, we are searching for a element which is not present in the list. In such cases, the list index() method raises a ValueError. Use this Compiler to compile your Python code.
Method 2: Using a for loop
We can also find the index of an element in a list by just iterating over it and checking if the current element is equal to the required element or not.
This is not the pythonic way to find the index of an element is we already have a built in function list.index() for this.
Code
Output:
Explanation
In this algorithm, we are searching for an element in a list by iterating through element of a list. If the element is found, its index is outputted, otherwise, it just says that "element is not found in the list".
Boost your career prospects with Scaler Topics Python certification course. Get started now and enhance your value in the job market.
Conclusion
In this article, "Find index of element in list Python", we have learnt that:
- The index of an element in a list can be found using the list.index() method.
- The start and end parameters of the list.index() method are optional.
- If the element is not found in the list, the list.index() method raises a ValueError.
- We can also find the index of an element in a list by iterating through the list till the element is found.