Get the Index or Position of Item in List in Python

featured Image

To find the index of an element from List in python, we can use the index() method and pass the element as an argument. It returns the index of the first occurrence of the element in the Python List.

Let’s understand it better using some examples.

Find Index of an Item using index() in a List

The index() method returns the position (index) of the first occurrence of a given value from a List class in Python.

Syntax:

list.index(item)

item = the specific element we are searching for. Let’s understand with an example.

Example:

my_list = ['a','b','c','d','e','f']
index = my_list.index('d')
print('The index is:',index)

Output:

The index is: 3

Now, let’s say the item has multiple occurrences in the given List. Then the index() method will only return the index of the first occurrence of the specified item and it will ignore the rest of it.

Example:

my_list = ['a','d','c','d','e','d']
index = my_list.index('d')
print('The index is:',index)

Output

The index is: 1

In the above example, we had ‘d‘ in indexes 1,3 and 5. And since index() only returns the first occurrence, we got the index as 1.

Find the index of an item between a range in a List

The index method lets us set a range within which we can search the index of an element in a Python List.

We just need to pass the start index and the end index and the index() method will search for the element within that range only.

Syntax:

list.index(item,start,end)

The argument start lets us specify the starting index of the range and the end lets us specify the end index of the range in the given List in Python.

Example:

my_list = ['a','d','c','d','e','f','g']
index = my_list.index('d', 2, 7)
print('The index is:',index)

Output:

The index is: 3

The method ignored the first ‘d ‘at index 1 in the list because the range starts from index 2.

Find indexes of all occurrences of an item in a Python List

Now, if we want to check for multiple occurrences of an element in a List, then index() method won’t work. This is because the index() method can only return the index of the first occurrence when the specified value is found in the Python List. And the rest will be ignored by the method.

So how to find the indexes for all the occurrences of the element?

Well to get all indexes from a Python List we can use the enumerate method or use a library called the NumPy.

1. Using Enumerate to find all indexes

The enumerate returns an enumerating object which contains the iterable item and adds a counter to it which starts from 0 .

Syntax:

enumerate(iterable, start=0)

Example

my_list = ['a','d','c']
print(list(enumerate(my_list)))
#[(0, 'a'), (1, 'd'), (2, 'c')]

Now using the for loop with the enumerated list and we can filter out the element from the Python List.

Here, in this example, we will find the indexes of the letter ‘d‘.

my_list = ['a','d','c','d']
indexes = [i for i, x in enumerate(my_list) if x == "d"]

print(indexes)
#[1, 3]

The iterator enumerate(my_list) returns us pairs (index, item) for each element in the List.

Next, we iterate through each pair using for loop with i and x as the loop variable. We then filter out the indexes of the element that matches the criteria (here x == 'd') using the if statement.

2. Using NumPy to find all indexes of an element in List

We can use the NumPy library to find multiple indexes of an element in a List.

Example:

import numpy as np

my_list = ['a','d','c','d']
item = 'd'
np_array = np.array(my_list)
item_index = np.where(np_array==item)
print(item_index)
#(array([1, 3]),)

Here, we have imported the NumPy library. Converted out python List to NumPy array using np.array()method and the used np.where() function to get the indexes of the element from the array.

If the item is not in the List in Python

If the search element is not present in the Python List using index() method, then we will get a ValueError in our terminal.

my_list = ['a','b','c','d','e','f']
index = my_list.index('g')
print('The index is:',index)

Here we have searched for the element ‘g‘ in the List.

File "main.py", line 2, in <module>
   index = my_list.index('g')
ValueError: 'g' is not in list  

Since the element is not in the List we get the “ValueError : ‘g’ is not in list” in our terminal as the output

To get the error we can try any of the two ways given below.

1. Using try-except statement

We can use the try except statement with the index() method to handle any ValueError in the Python program.

Example:

my_list = ['a','b','c','d','e','f']
try:
    index = my_list.index('g')
    print('The index is:',index)
except ValueError:
    print('Item not Found')

Since the item ‘g‘ is not present in the List, we will get the output as

Item not Found

2. Using if else conditional statement

If you want to check if the item exists in the List before running the index() method, then we can use the if else statement.

Example:

my_list = ['a','b','c','d','e','f']
item = 'g'
if item in my_list:
    index = my_list.index(item)
    print('The index is:',index)
else:
    print('Item Not Found')

Output:

Item Not Found

In this example, we check if the item is in the Python list. If yes, then it prints out the index of the element, else it prints ‘Item Not Found‘ on the terminal.


Related Topics:

How to split a list into multiple list using python

Split String and get the first element using python

Remove Duplicates from List in Python

Remove the Last N element from a List in Python

Python – Insert an element at specific index in a list

Sort List or Dictionary by two keys in Python

How to flatten nested list in python (5 ways)

Remove Duplicates from List in Python

Related Posts

merge json files in python

How to merge JSON files in python

JSON (JavaScript Object Notation) is a data format used for storing, transferring, and visualizing data. Its simple structure of key:value pairs and array data types makes JSON an easy and…

Read more
Install python pip in ubuntu

How to Install Pip(pip3) in Ubuntu Linux 22.04

Pip is a package manager for Python that allows you to install and manage additional Python packages that are not part of the Python standard library. Pip makes it easy…

Read more
featured Image

How to Write If-Else Statements in One Line in Python

If-else statements are a fundamental concept in Python and other programming languages. They allow you to execute different blocks of code based on whether a condition is true or false….

Read more

Leave a Reply

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