Open In App

Python List index()

Last Updated : 20 Jun, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

List index() method searches for a given element from the start of the list and returns the position of the first occurrence.

Example:

Python
# list of animals
Animals= ["cat", "dog", "tiger"]
# searching positiion of dog
print(Animals.index("dog"))

Output
1


Definition of Python List index()

Python list index() method is used to find position of element in list Python.

It returns the position of the first occurrence of that element in the list. If the item is not found in the list, index() function raises a “ValueError” error.

List index() Method Syntax

list_name.index(element, start, end) 

Parameters: 

  • element – The element whose lowest index will be returned.
  • start (Optional) – The position from where the search begins.
  • end (Optional) – The position from where the search ends.

Return: Returns the lowest index where the element appears.

Error: If any element which is not present is searched, it raises a ValueError.

How to Find Index of an Element in a List?

Using index() method in Python, you can find position of the first occurrence of an element in list.

Example:

Python
#List of fruits
fruits = ["apple", "banana","cherry","apple"]
#Searching index of apple
print(fruits.index("apple"))

Output
0


More Example on List index() Method

We will cover different examples to find the index of element in list using Python, and explore different scenarios while using list index() method, such as:

  • Find the index of the element
  • Working on the index() With Start and End Parameters
  • Working of the index() With two Parameters only
  • Index of the Element not Present in the List
  • How to fix list index out of range

Example 1: Find the index of the element

Finding an index of ‘bat’ using index() on Python List list2.

Python
# list of items
list2 = ['cat', 'bat', 'mat', 'cat', 'pet']

# Will print the index of 'bat' in list2
print(list2.index('bat'))

Output
1


Example 2: Working on the index() With Start and End Parameters

In this example, we find an element in list python, the index of an element of 4 in between the index at the 4th position and ending with the 8th position.

Python
# list of items
list1 = [1, 2, 3, 4, 1, 1, 1, 4, 5]

# Will print index of '4' in sublist
# having index from 4 to 8.
print(list1.index(4, 4, 8))

Output
7


Example 3: Working of the index() With two Parameters only

In this example, we will see when we pass two arguments in the index function, the first argument is treated as the element to be searched and the second argument is the index from where the searching begins. 

Python
# list of items
list1 = [6, 8, 5, 6, 1, 2]

# Will print index of '6' in sublist
# having index from 1 to end of the list.
print(list1.index(6, 1))

Output
3


Example 4: Index of the Element not Present in the List

Python List index() raises ValueError when the search element is not present inside the List.

Python
# Python3 program for demonstration
# of index() method error

list1 = [1, 2, 3, 4, 1, 1, 1, 4, 5]

# Return ValueError
print(list1.index(10))

Output: 

Traceback (most recent call last):
File "/home/b910d8dcbc0f4f4b61499668654450d2.py", line 8, in
print(list1.index(10))
ValueError: 10 is not in list

Example 5: How to fix list index out of range using Index()

Here we are going to create a list and then try to iterate the list using the constant values in for loops.

Python
li = [1,2 ,3, 4, 5]

for i in range(6):
    print(li[i])

Output:

1
2
3
4
5
IndexError: list index out of range

Reason for the error: The length of the list is 5 and if we are an iterating list on 6 then it will generate the error.

Solving this error without using len():

To solve this error we will take the count of the total number of elements inside the list and run a loop after that in the range of that count.

Python
li = [1, 5, 3, 2, 4]
count=0

for num in li:
  count+=1
  
for i in range(count):
    print(li[i])

Output
1
5
3
2
4


Python list index() method is very useful when searching for an element in a list. Python list index() function works best in a list where every element is unique.

Hope you learnt about how to use index() function in Python? after reading this article.

Also Read:

Python List index() – FAQs

Why is list index out of range?

The “list index out of range” error occurs when you try to access an index that does not exist in the list. For example, if you have a list of length 5 and you try to access the element at index 10, you’ll get this error because the index is beyond the bounds of the list.

What does the index() method do in Python lists?

The index() method in Python lists returns the first occurrence of the specified value. It raises a ValueError if the value is not found in the list.

Can I specify a range to search within using the index() method?

Yes, you can specify a range to search within using the index() method by providing optional start and end parameters. The method will search for the value only within the specified range.

How do I use the index() method to find the index of a specific value in a list?

Here is how you can use the index() method to find the index of a specific value in a list:

my_list = ['a', 'b', 'c', 'd', 'b']
index_of_b = my_list.index('b') # Finds the first occurrence of 'b'
print(index_of_b) # Output: 1

# With start and end parameters
index_of_b_in_range = my_list.index('b', 2, 5) # Finds 'b' in the range index 2 to 4
print(index_of_b_in_range) # Output: 4

What happens if the index is out of range in Python?

If you try to access an index that is out of range in Python, it raises an IndexError with the message “list index out of range”. This happens because the index you’re trying to access does not exist within the list’s bounds.

Example:

my_list = [1, 2, 3]
print(my_list[5]) # Raises IndexError: list index out of range


Previous Article
Next Article

Similar Reads

Python | Sort list of list by specified index
We can sort the list of lists by using the conventional sort function. This sort the list by the specified index of lists. Let's discuss certain ways in which this task can be performed using Python. Method 1: Using the bubble sort algorithm Bubble sort is a simple sorting algorithm that repeatedly steps through the list to be sorted, compares each
8 min read
Python | Replace elements in second list with index of same element in first list
Given two lists of strings, where first list contains all elements of second list, the task is to replace every element in second list with index of elements in first list. Method #1: Using Iteration C/C++ Code # Python code to replace every element # in second list with index of first element. # List Initialization Input1 = ['cut', 'god', 'pass']
5 min read
Python | Add list elements with a multi-list based on index
Given two lists, one is a simple list and second is a multi-list, the task is to add both lists based on index. Example: Input: List = [1, 2, 3, 4, 5, 6] List of list = [[0], [0, 1, 2], [0, 1], [0, 1], [0, 1, 2], [0]] Output: [[1], [2, 3, 4], [3, 4], [4, 5], [5, 6, 7], [6]] Explanation: [1] = [1+0] [2, 3, 4] = [0+2, 1+2, 2+2] [3, 4] = [3+0, 3+1] [4
5 min read
Python - Sort dictionaries list by Key's Value list index
Given list of dictionaries, sort dictionaries on basis of Key's index value. Input : [{"Gfg" : [6, 7, 8], "is" : 9, "best" : 10}, {"Gfg" : [2, 0, 3], "is" : 11, "best" : 19}, {"Gfg" : [4, 6, 9], "is" : 16, "best" : 1}], K = "Gfg", idx = 0 Output : [{'Gfg': [2, 0, 3], 'is': 11, 'best': 19}, {'Gfg': [4, 6, 9], 'is': 16, 'best': 1}, {'Gfg': [6, 7, 8],
14 min read
Python - Filter the List of String whose index in second List contains the given Substring
Given two lists, extract all elements from the first list, whose corresponding index in the second list contains the required substring. Examples: Input : test_list1 = ["Gfg", "is", "not", "best", "and", "not", "CS"], test_list2 = ["Its ok", "all ok", "wrong", "looks ok", "ok", "wrong", "thats ok"], sub_str = "ok" Output : ['Gfg', 'is', 'best', 'an
10 min read
Numpy: Index 3D array with index of last axis stored in 2D array
NumPy, or Numerical Python, is a powerful library for efficient numerical computation in Python. One of the key features of NumPy is its ability to perform advanced indexing, which allows to access and manipulate specific elements of an array based on complex conditions. In this article, we will explore how to index a 3D array using a 2D array of i
5 min read
Python | Index of Non-Zero elements in Python list
Sometimes, while working with python list, we can have a problem in which we need to find positions of all the integers other than 0. This can have application in day-day programming or competitive programming. Let's discuss a shorthand by which we can perform this particular task. Method : Using enumerate() + list comprehension This method can be
6 min read
Python | Index specific cyclic iteration in list
The problem of cyclic iteration is quite common, but sometimes, we come through the issue in which we require to process the list in a way in which it is cyclically iterated to starting from a specific index. Let's discuss certain ways in which this problem can be solved. Method #1 : Using % operator + loop The % operator can be used to cycle the o
6 min read
Python | Subgroups of i'th index size in list
Sometimes we need to group elements and grouping techniques and requirements vary accordingly. One such way to group the elements is by the i'th size in list which stores the dictionary of index keys with values as list elements of subsequent size i. Input : [4, 7, 8, 10, 12, 15, 13, 17, 14, 5] Output: {1: [4], 2: [7, 8], 3: [10, 12, 15], 4: [13, 1
3 min read
Python | Equate two list index elements
Sometimes we need to link two list from the point of view of their index elements and this kind of problem comes mostly in places where we need to display in formatted form the linkage of two lists with one another. This a very specific problem, but can be useful whenever we need a possible solution. Let's discuss certain ways in which this can be
8 min read