The Wayback Machine - https://web.archive.org/web/20240910195322/https://www.geeksforgeeks.org/python-list-index/
Open In App

Python List index()

Last Updated : 30 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 - 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 | Returning index of a sorted list
Sort a list in python and then return the index of elements in sorted order. Examples: Input : [2, 3, 1, 4, 5] Output : [2, 0, 1, 3, 4] After sorting list becomes [1, 2, 3, 4, 5] and their index as [2, 0, 1, 3, 4] Input : [6, 4, 7, 8, 1] Output : [4, 1, 0, 2, 3] After sorting the list becomes [1, 4, 6, 7, 8] and their index as [4, 1, 0, 2, 3]. Meth
3 min read
Python - Append List every Nth index
Given 2 list, append list to the original list every nth index. Input : test_list = [3, 7, 8, 2, 1, 5, 8], app_list = ['G', 'F', 'G'], N = 3 Output : ['G', 'F', 'G', 3, 7, 8, 'G', 'F', 'G', 2, 1, 5, 'G', 'F', 'G', 8] Explanation : List is added after every 3rd element.Input : test_list = [3, 7, 8, 2, 1, 5, 8, 9], app_list = ['G', 'F', 'G'], N = 4 O
5 min read
Get index in the list of objects by attribute in Python
In this article, we'll look at how to find the index of an item in a list using an attribute in Python. We'll use the enumerate function to do this. The enumerate() function produces a counter that counts how many times a loop has been iterated. We don't need to import additional libraries to utilize the enumerate() function because it's built-in t
2 min read
Python Indexerror: list assignment index out of range Solution
In python, lists are mutable as the elements of a list can be modified. But if you try to modify a value whose index is greater than or equal to the length of the list then you will encounter an Indexerror: list assignment index out of range. Python Indexerror: list assignment index out of range ExampleIf ‘fruits’ is a list, fruits=[‘Apple’,’ Banan
3 min read
Python List Index Out of Range - How to Fix IndexError
In Python, the IndexError is a common exception that occurs when trying to access an element in a list, tuple, or any other sequence using an index that is outside the valid range of indices for that sequence. List Index Out of Range Occur in Python when an item from a list is tried to be accessed that is outside the range of the list. Before we pr
3 min read
Python | Print list after removing element at given index
In this article, we will see how we can remove elements at a given index and print the list afterward. Example Input1: list = [10, 20, 30, 40, 50] index = 2 Output1: [10, 20, 40, 50] Input2: list = [10, 20, 40, 50] index = 0 Output2: [20, 40, 50] Print list after removing element at given indexBelow are the methods by which we can remove element at
3 min read
Get Index of Multiple List Elements in Python
In Python, retrieving the indices of specific elements in a list is a common task that programmers often encounter. There are several methods to achieve this, each with its own advantages and use cases. In this article, we will explore some different approaches to get the index of multiple list elements in Python. Get Index Of Multiple List Element
3 min read
Python | Convert list of string to list of list
Many times, we come over the dumped data that is found in the string format and we require it to be represented in the actual list format in which it was actually found. This kind of problem of converting a list represented in string format back to la ist to perform tasks is quite common in web development. Let's discuss certain ways in which this
7 min read
Python | Pandas Index.insert()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas Index.insert() function make new Index inserting new item at location. This function also follows Python list.append() semantics
2 min read
Python | Pandas Index.get_slice_bound()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas Index.get_slice_bound() function calculate slice bound that corresponds to given label and it returns the value. The function ret
2 min read
Readability Index in Python(NLP)
Readability is the ease with which a reader can understand a written text. In natural language, the readability of text depends on its content (the complexity of its vocabulary and syntax). It focuses on the words we choose, and how we put them into sentences and paragraphs for the readers to comprehend. Our main objective in writing is to pass alo
6 min read
Python | Pandas Index.delete()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas Index.delete() function returns a new object with the passed locations deleted. We can pass more than one locations to be deleted
2 min read
Python | Pandas Index.drop_duplicates()
Pandas Index.drop_duplicates() function return Index with duplicate values removed in Python. Syntax of Pandas Index.drop_duplicates() Syntax: Index.drop_duplicates(labels, errors='raise') Parameters : keep : {‘first’, ‘last’, False} ‘first’ : Drop duplicates except for the first occurrence.(default)‘last’ : Drop duplicates except for the last occu
2 min read
Python | Pandas Series.str.index()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas str.index() method is used to search and return lowest index of a substring in particular section (Between start and end) of ever
3 min read
Python | Pandas Index.dropna()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas Index.dropna() function return Index without NA/NaN values. All the missing values are removed and a new object is returned which
2 min read
Python | Pandas Index.contains()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas Index.contains() function return a boolean indicating whether the provided key is in the index. If the input value is present in
2 min read
Python | Pandas Series.nonzero() to get Index of all non zero values in a series
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas Series.nonzero() is an argument less method. Just like it name says, rather returning non zero values from a series, it returns i
2 min read
numpy.index() in Python
numpy.core.defchararray.index(arr, substring, start=0, end=None): Finds the lowest index of the sub-string in the specified range But if substring is not found, it raises ValueError. Parameters: arr : array-like or string to be searched. substring : substring to search for. start, end : [int, optional] Range to search in. Returns : An integer array
1 min read
Python | Pandas Index.difference()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.Pandas Index.difference() function return a new Index with elements from the index that are not in other. The function automatically sort
2 min read
Python | Pandas Index.append()
Python is an excellent language for data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas are one of those packages, making importing and analyzing data much easier. Pandas Index.append() The function is used to append a single or a collection of indices together. In the case of a collection of indices,
2 min read
Python | Pandas Index.any()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas Index.any() function checks if any of the elements in the index are true or not. It returns one single boolean value if axis is n
2 min read
Python | Pandas Index.all()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas Index.all() function checks if all the elements in the index are true or not. It returns one single boolean value if axis is not
2 min read
Python | Pandas Index.astype()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas Index.astype() function create an Index with values cast to dtypes. The class of a new Index is determined by dtype. When convers
2 min read
Python | Pandas Index.asof()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas Index.asof() function returns return the label from the index, or, if not present, the previous one. Assuming that the index is s
2 min read
Python | Pandas Index.argmin()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas Index.argmin() function returns the indices of the minimum value present in the input Index. If we are having more than one minim
2 min read
Python | Pandas Index.argsort()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas Index.argsort() function returns the integer indices that would sort the index. By default the sorting order has been set to incr
2 min read