Skip to content

Python List index() function

  • by

The index() function in Python is a built-in method for lists that allows you to find the index of a specified element within the list. It returns the index of the first occurrence of the specified element.

Here’s the syntax of the index() function:

list.index(element[, start[, end]])
  • element: The element you want to find the index of.
  • start (optional): The index from which the search should begin. It defaults to 0.
  • end (optional): The index at which the search should end. The element at this index is not included in the search. It defaults to the length of the list.

Python List index() function example

Here’s an example of how to use the index() function:

my_list = [10, 20, 30, 40, 50, 30, 60]

# Find the index of the first occurrence of the element 30
index = my_list.index(30)
print("Index of 30:", index)

# Find the index of the element 30, starting from index 3
index = my_list.index(30, 3)
print("Index of 30 (starting from index 3):", index)

# Find the index of the element 30, searching only up to index 5
index = my_list.index(30, 0, 5)
print("Index of 30 (up to index 5):", index) 

Output:

Python List index() function

Here’s a more comprehensive example that demonstrates the usage of the index() function in various scenarios:

# Sample list
fruits = ["apple", "banana", "orange", "banana", "apple", "mango", "kiwi"]

# Find the index of the first occurrence of "banana"
b_index = fruits.index("banana")
print(b_index)

# Find the index of "banana" starting from index 2
b_index_start_from_2 = fruits.index("banana", 2)
print(b_index_start_from_2)

# Find the index of "banana" between index 2 and 4
b_index_between_2_and_4 = fruits.index("banana", 2, 4)
print(b_index_between_2_and_4)

# Handling the ValueError using a try-except block
try:
    b_index_between_2_and_4 = fruits.index("banana", 2, 4)
    print(b_index_between_2_and_4)
except ValueError:
    print("'banana' not found in the specified range")

# Find the index of "grape" (which is not in the list)
try:
    grape_index = fruits.index("grape")
    print(grape_index)
except ValueError:
    print("'grape' not found in the list")

In this example, the index() function is used to find the index of specific elements in the list. It also demonstrates how to handle cases where the element is not found in the list by using a try-except block to catch the ValueError that’s raised in such situations.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *