Back to articles list Articles
8 minutes read

How to Get the Index of an Item in a List in Python

Do you want to practice data structures in Python? In this article, I explain every detail about getting the index of an item in a Python list, a fundamental data structure used in Python programs.

The list is one of the built-in data structures in Python. It is represented as a collection of data points in square brackets and can store values with different data types. The Python list is a versatile and efficient data structure, so it is of great importance to know how to manipulate and interact for designing efficient Python programs.

Let’s see an example of a Python list.

>>> names = ["Jane", "James", "Matt", "Ashley", "Oliver"]
>>> type(names)
list

One of the operations we perform on lists is to get the index of an item. Each item in a Python list has an associated index that may be used for accessing that item.

We can use the index() method to find the index of an item.

>>> names = ["Jane", "James", "Matt", "Ashley", "Oliver"]
>>> names.index("Matt")
2

The index starts at 0. Since “Matt” is the third item in the names list, its index is 2.

In this article, we go over several examples to learn the details of the index() method as well as other ways to find the index of an item in a Python list.

Examples and hands-on experience are essential for learning Python or any other programming language. LearnPython.com has lots of interactive courses and tracks that offer an active learning experience with exercises. The course “Python Data Structures in Practice” focuses on built-in data structures of Python: list, tuple, dictionary, and set. The course has 118 interactive exercises on solving fundamental programming problems with basic data structures.

How to Use the index() Method

The index() method gives us a straightforward way to get the index of an item. However, there are some things to keep in mind.

Since lists can have duplicate items, there may be multiple occurrences of the item we are looking for. In such cases, the index() method returns the index of the first occurrence of that item. Let’s review an example that demonstrates this.

>>> names = ["Jane", "James", "Matt", "Ashley", "Oliver", "James"]
>>> names.index("James")
1

There are two “James” values in the names list above. When we use the index() method to get the index of “James”, it returns 1, the index of the first occurrence of “James”.

When the Item Is Not in the Python List

The item we look for may not exist in the list. If it does not, the index() method raises a value error.

>>> names = ["Jane", "James", "Matt", "Ashley", "Oliver", "James"]
>>> names.index("Alex")
ValueError: 'Alex' is not in list

To make the script continue executing in such cases, we may implement a try-except block. The following code block uses a for loop to get the index of the given items in the names list and prints the result. Thanks to the try-except block, the code prints an informative output instead of raising a value error if the item is not in the list.

>>> names = ["Jane", "James", "Matt", "Ashley", "Oliver", "James"]
>>> items_to_check = ["Matt", "Alex"]
>>> for item in items_to_check:
>>> 	  try:
>>>		print(f"The index of {item} is {names.index(item)}.")
>>>     except ValueError:
>>> 		print(f"{item} is not in the list.")
The index of Matt is 2.
Alex is not in the list.

Alternatively, we may use an if statement to first check if the item exists in the list and then try to get its index.

>>> names = ["Jane", "James", "Matt", "Ashley", "Oliver", "James"]
>>> items_to_check = ["Matt", "Alex"]
>>> for item in items_to_check:
>>> 	  if item in names:
>>>		print(f"The index of {item} is {names.index(item)}.")
The index of Matt is 2.

The start and stop Parameters

The index() method may also be used for getting the index of an item in a particular subsequence of a Python list. We define a subsequence to search using the start and stop parameters. For instance, if we want to look for an item in the first 5 items, we set the values of the start and stop parameters as 0 and 5, respectively.

The following code block looks for “Oliver” in the subsequence that starts from the first item (index 0) and ends with the third item (index 2). The upper bound is exclusive, so the subsequence defined by 0 and 3 only includes the items “Jane”, “James”, and “Matt”.

>>> names = ["Jane", "James", "Matt", "Ashley", "Oliver", "James"]
>>> names.index("Oliver", 0, 3)
ValueError: 'Oliver' is not in list

Let’s now search for “Oliver” in the second part of the list.

>>> names = ["Jane", "James", "Matt", "Ashley", "Oliver", "James"]
>>> names.index("Oliver", 3, 6)
4

In the code block above, we check the sequence of “Ashley”, “Oliver”, and “James”. Although “Oliver” is the second item in this sequence, the index() method returns 4, the index of “Oliver” in the entire list. Even when we search for an item in a subsequence, the returned index is computed relative to the beginning of the full sequence (i.e., the entire list) rather than the start argument.

Drawbacks of the index() Method in Python

The index() Method Returns the First Occurrence of the Item in a List

The index() method only returns the first occurrence of the searched item. If there are multiple occurrences and we want to know where all of them are, we need a different approach.

One option is to use the enumerate function in a list comprehension. Let’s see an example to demonstrate this case using an example we have already seen.

>>> names = ["Jane", "James", "Matt", "Ashley", "Oliver", "James"]
>>> [i for i, e in enumerate(names) if e == "James"]
[1, 5]

The Python built-in enumerate function takes an iterable and an optional start argument. It iterates over the iterable while keeping track of the count. The count value may be used as the index of the item. The default value of the optional start argument is 0, which is what we need when working on lists because the Python list index also starts from 0.

We may also use this method to search for an item in a particular subsequence of a Python list. Unlike the index() method, we do not have the start and stop parameters to define the subsequence. However, we can always define them by writing the index values next to the list name in square brackets. For example, the enumerate function in the code block below iterates over a subsequence starting from the fourth item up to the last one.

>>> names = ["Jane", "James", "Matt", "Ashley", "Oliver", "James"]
>>> [i for i, e in enumerate(names[3:]) if e == "James"]
[2]

It is important to note that the return index value above is relative to the starting point of the subsequence. This is because the enumerate function starts counting from 0. We may customize it to find the index value relative to the first item of the list using the start parameter of the enumerate function.

>>> names = ["Jane", "James", "Matt", "Ashley", "Oliver", "James"]
>>> [i for i, e in enumerate(names[3:], start=3) if e == "James"]
[5]

Searching a List Using a for Loop

What the list comprehension with the enumerate function does may also be done by writing a for loop as follows:

>>> names = ["Jane", "James", "Matt", "Ashley", "Oliver", "James"]
>>> james_index = []
>>> count = [0]
>>>
>>> for item in names: 
>>> 	  if item == "James":
>>>		james_index.append(count)
>>>     count += 1
>>>
>>> james_index
[1, 5]

This option is more prone to mistakes than list comprehension. For example, if the increment of the count variable is placed incorrectly, then the resulting index values are wrong. The enumerate function does this increment for us automatically. On the other hand, the for loop is more versatile; we can do what we want in a for loop.

Linear Time Complexity of the index() Method

Another drawback of the index() method is that it has a linear time complexity in its length. If we have a list of 1 million items and the item we are searching for is the last one, then the search may take a very long time. The index() method is a hindrance in this case, and we should consider a different data structure.

Moreover, if we place an if statement before the index() method to make sure the item is in the list, we go over the entire list of 1 million items before every search. This makes the situation even more complex and time-consuming.

Leveraging Python Lists

The Python list is a fundamental data structure. In this article, we have learned about the index() method of lists. There are many other methods we may use on lists such as append and insert. It is important to know these methods to use the lists efficiently and properly. See this great article if you are looking for more exercises on lists.

Python is one of the most used programming languages across a wide range of domains. It is easy to learn, making it the top choice for those who want to learn to program or do not come from a technical background. When you learn Python, you have many job opportunities in tech that are also highly rewarding.

So why wait? Start learning Python today!