In this Python tutorial, we will discuss the Python List index() method. It is an essential method of the list class that allows us to find the index of the first occurrence.
List index() method in Python
Below are the topics that we are doing to discuss in this article:
- Introduction to Python List index() method
- Syntax of the index() method
- Purpose and use cases of the index() method
Python List index() method
The index() method is a built-in Python method for lists, used to find the index of the first occurrence of a specified element in a Python list.
The syntax for the index() method is as follows:
list.index(element, start, end)
Arguments:
- element (required): The element whose index needs to be found in the list.
- start (optional): The starting index from which the search should begin. Defaults to 0 if not specified.
- end (optional): The ending index until which the search should be performed. Defaults to the length of the list if not specified.
The index() method returns the index of the first occurrence of the specified element if found in the Python list, within the specified start and end indices.
Note: If the element is not found, a ValueError is raised.
insert() method in Python List Examples
Let’s dive into some examples to see the Python insert() method in action.
Example#1 Basic usage:
states = ['California', 'Texas', 'New York', 'Florida', 'Illinois']
index = states.index('New York')
print(index)
In this example, we have a Python list called states
, which contains the names of five US states. We want to find the index of the state ‘New York’ in this list. The index() method is used to get the index of ‘New York’, which is then printed.
The output will be 2
, as ‘New York’ is the third element in the list and has an index of 2 (Python uses zero-based indexing).
Output:
Example#2 Using Start and End Arguments
states = ['California', 'Texas', 'New York', 'Florida', 'Illinois', 'New York']
index = states.index('New York', 3)
print(index) # Output: 5
index = states.index('Illinois', 1, 4)
print(index) # Raises ValueError, as 'Illinois' is not found within indices 1 to 4.
In this example, we have an updated states
list with an additional occurrence of ‘New York’. We demonstrate the use of optional start and end arguments with the Python index() method.
In the first part, we use the index() method to find the index of ‘New York’ starting from the 3rd index (Florida). The output will be 5
, as the second occurrence of ‘New York’ is found at index 5.
In the second part, we search for ‘Illinois’ within indices 1 to 4. Since ‘Illinois’ is not found within this range, a ValueError is raised.
Output:
Example#3 Handling ValueError
states = ['California', 'Texas', 'New York', 'Florida', 'Illinois']
try:
index = states.index('Nevada')
print(index)
except ValueError:
print("Element not found in the list.")
In this example, we attempt to find the index of the state ‘Nevada’ in the states
list. Since ‘Nevada’ is not present in the Python list, the index() method raises a ValueError.
By using a try-except block, we can handle this exception gracefully and print a custom message to inform the user that the element was not found in the list.
Output:
Example#4 Finding the Index of a String in a List of Mixed Data Types
mixed_data = [3.14, 'Florida', 42, 'New York', 7]
index = mixed_data.index('Florida')
print(index)
In this example, we have a Python list called mixed_data
containing elements of different data types, including strings, integers, and floats. We want to find the index of the string ‘Florida’ in this list, which represents a US state.
The Python list index() method is used to get the index of ‘Florida’, which is then printed.
Output:
Example#5 Finding the Index of a Tuple in a List of Tuples
coordinates = [(1, 2), (3, 5), (4, 7), (6, 9), (8, 11)]
index = coordinates.index((4, 7))
print(index)
In this example, we have a Python list of tuples called coordinates
, each tuple containing an x and y coordinate. We want to find the index of the tuple (4, 7) in this list. The index() method is used to get the index of the tuple, which is then printed.
Output:
Example#6 Using the Index Method in a Loop
cities = ['New York', 'Los Angeles', 'Chicago', 'Los Angeles', 'Houston', 'Los Angeles']
start = 0
while True:
try:
index = cities.index('Los Angeles', start)
print(f'Los Angeles found at index {index}')
start = index + 1
except ValueError:
break
In this example, we have a list of US cities called cities
. We want to find and print the indices of all occurrences of the city ‘Los Angeles’ in the Python list. To do this, we use for loop and the index() method with the start argument.
Output:
Conclusion
The Python List index() method is a valuable tool for working with Python lists. It allows us to find the index of the first occurrence of a specified element in a list, within optional start and end indices.
Keep in mind the potential for a ValueError when the specified element is not found, and handle the exception accordingly.
You may also like to read the following articles:
- Python List copy() method [With Examples]
- Python program to sort list of tuples
- How to convert Python Dictionary to a list [9 Different ways]
- Find Largest and Smallest Number in Python Without List
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.