How to Find the Index of a List Element in Python?

Introduction

Lists are the built-in data type in Python used to store items in an ordered sequence. You will definitely use lists in most of your projects if you are programming in Python. So take your time and invest a good hour or so to study this guide carefully.

📖 Note: In Python, list elements start at index 0 (the first item is indexed 0) and we can keep adding more items.
 

Problem Formulation: Given a list. How will you find the index of a list element?

Example: In the following, the list consists of names of books as its elements. You have to find the index of the element/book – “Rich Dad Poor Dad“.

# A list of books
lst = ["Book Thief", "Harry Potter and the Philosopher's Stone", "Rich Dad Poor Dad", "The Great Gatsby"]
print("Available books:")
print(lst)
# Accessing Index of the List Element
x = lst.index('Rich Dad Poor Dad')
print("Book index- ", x)

Output:

Available books:
['Book Thief', "Harry Potter and the Philosopher's Stone", 'Rich Dad Poor Dad', 'The Great Gatsby']
Book index-  2

Now that you have an idea of the topic let us dive into the mission-critical question and learn the methods to find the index of a list element.

✏️Method 1: Using index() method

The simplest way to get the index of a list element is to use the index() method. To use the index() method, you just need to pass the element as an argument.

Definition and Usage: The list.index(value) method returns the index of the value argument in the list. You can use optional start and stop arguments to limit the index range where to search for the value in the list. If the value is not in the list, the method throws a ValueError.

Syntax:

lst.index(element)

Solution:

# A list of books
lst = ["Book Thief", "Harry Potter and the Philosopher's Stone", "Rich Dad Poor Dad", "The Great Gatsby"]
print("Available books:")
print(lst)

# Accessing Index of the List Element
x = lst.index('Rich Dad Poor Dad')
print("Book index- ", x)

Output:

Available books:
['Book Thief', "Harry Potter and the Philosopher's Stone", 'Rich Dad Poor Dad', 'The Great Gatsby']
Book index-  2

💣Find The Index when List has Duplicate elements

The index() method is used to find the first lowest index of the element, i.e. in case of duplicate elements it will return the first element’s index as shown in the example given below.

Example:

# A list of fruits
lst = ["Apple", "Mango", "Banana", "Mango", "Cherry"]
print("Fruits:")
print(lst)

# Accessing Index of the List Element
x = lst.index('Mango')  # Duplicate element
print("Index of Mango: ", x)

Output:

Fruits:
['Apple', 'Mango', 'Banana', 'Mango', 'Cherry']
Index of Mango:  1

💣Finding Index Within A Range

In the previous example you saw how index() method works with duplicate elements in a list. What if you want to search the index of a duplicate element from a specific range in the list?

The index() method also allows you to define the start and end positions for the list. It will only search the index within the range from start to end. This helps when you have duplicate elements and you don’t want to return the element at the start of the list.

Syntax:

lst.index(element [start[ end]])

Example:

# A list of fruits
lst = ["Apple", "Mango", "Banana", "Mango", "Cherry"]
print("Fruits:")
print(lst)

# Defining start end for the Element
ele = "Mango"
start = 2
end = 4

# Accessing Index of the List Element
x = lst.index(ele, start, end)
print("Index of Mango: ", x)

Output:

Fruits:
['Apple', 'Mango', 'Banana', 'Mango', 'Cherry']
Index of Mango:  3

Explanation: As we have specified the start and end of the list, only the indices within the range of index[2-4] of the list are considered. Hence, we get the index of the second duplicate element.

💥What happens when you try to find the index of an element that is not present in the given list?

When we use the index() method on an element that is not present in the list, we get a ValueError.

Example:

# A list of fruits
lst = ["Apple", "Mango", "Banana", "Mango", "Cherry"]
print("Fruits:")
print(lst)

# Accessing Index of the List Element
x = lst.index('Pear')  # Element not in the list
print("Index- ", x)

Output:

Fruits:
['Apple', 'Mango', 'Banana', 'Mango', 'Cherry']
Traceback (most recent call last):
  File "E:\program\main.py", line 7, in <module>
    x = lst.index('Pear') # Element not in the list
ValueError: 'Pear' is not in list

Now, what if you want to find the index of all the duplicate elements in the list? That brings us to the next solution which will help us to overcome our problems with duplicate elements.

✏️Method 2: Using a For Loop

Another effective way to find the index of a list element is to use a simple for loop. The for loop along with the range() function and the len() function allows you to iterate over the elements of the list and keep a track of their indexes. This approach also helps to return the index of all the duplicate elements in the list which is not possible using the index() method.

Example:

# A list of fruits
lst = ["Apple", "Mango", "Banana", "Mango", "Cherry", "Pear", "Mango"]
print("Fruits:")
print(lst)

# Empty list to store the index in case of duplicate elements
indexes = []

# Accessing Index of the List Element using for loop
for i in range(0, len(lst)):
    if lst[i] == 'Mango':
        indexes.append(i)

print("Indexes of element Mango: ", indexes)

Output:

Fruits:
['Apple', 'Mango', 'Banana', 'Mango', 'Cherry', 'Pear', 'Mango']
Index for Mango:  [1, 3, 6]

✏️Method 3: Using enumerate

In Python, enumerate() is an in-built function that counts the elements in the sequence provided. The function takes an iterable object as an input and returns an object with a counter to each element.

Let’s have a look at the following example to understand how we can use the enumerate method and find the index of an element within a list in Python.

# A list of fruits
lst = ["Apple", "Mango", "Banana", "Mango", "Cherry", "Pear", "Mango"]
print("Fruits:")
print(lst)

# Empty list to store the index in case of duplicate elements
indexes = []

# Accessing Index of the List Element using enumerate()
for c, ele in enumerate(lst):  # c is the count of elements
    if ele == 'Mango':
        indexes.append(c)

print("Index for Mango: ", indexes)

Output:

Fruits:
['Apple', 'Mango', 'Banana', 'Mango', 'Cherry', 'Pear', 'Mango']
Index for Mango:  [1, 3, 6]

Recommended Tutorial: Python enumerate() — A Simple Illustrated Guide 

✏️Method 4: Using The NumPy Library 

NumPy is a library used for arrays in Python. It’s an abbreviation for Numerical Python. We can use this library to find the index of the list element. In order to utilize this library, we have to first install it.

pip install numpy

After installing the library import it into your code.

import numpy as np

Now, you can use this module to find the index of the list element.

Example:

# Importing numpy library
import numpy as np

# A list of fruits
lst = ["Apple", "Mango", "Banana", "Mango", "Cherry", "Pear", "Mango"]
print("Fruits:")
arr = np.array(lst)
print(arr)

# Accessing Index of the List Element using numpy
indexes = np.where(arr == 'Mango')[0]

print("Index for Mango: ", indexes)

Output:

Fruits:
['Apple' 'Mango' 'Banana' 'Mango' 'Cherry' 'Pear' 'Mango']
Index for Mango:  [1 3 6]	

Conclusion

Therefore, you learned about the various methods to find the index of the list element in Python. To keep learning, please subscribe to our channel and blog tutorials and stay tuned for more interesting tutorials.

Post Credits: Shubham Sayon and Rashi Agarwal


  • Do you want to master the most popular Python IDE fast?
  • This course will take you from beginner to expert in PyCharm in ~90 minutes.
  • For any software developer, it is crucial to master the IDE well, to write, test and debug high-quality code with little effort.
The Complete Guide to PyCharm

Join the PyCharm Masterclass now, and master PyCharm by tomorrow!