Python Find Index Of An item In List – Detailed Guide

Python list allows you to store multiple items in a single variable.

You can find the index of an item in the list in python using the list.index() method.

In this tutorial, you’ll learn the different ways to find the index of an item in the list.

If you’re in Hurry

You can use the below code snippet to find the index of an element.

list = [1,5,7,9,23,56]

list.index(5)

Where, 5 is existing in the second position in the list. Since the index is 0 based, you’ll see the output as 1.

Output

 1

If You Want to Understand Details, Read on…

In this detailed tutorial, you’ll learn the different methods available to find the index of an element in the list.

Python List Index() With Examples

You can find the index of an item in the list using List.index() method.

Syntax

list.index(element, start_pos, end_pos)

Where,

  • elementRequired. Element to Find in the list
  • start_posOptional. If you want to find an item starting from a specific position rather checking entire list
  • end_posOptional. If you want to find an item until a specific position .

You can use the start position and end position if you want to check if an item is available in the list within the specified range.

Exception

If the item is not available in the list, then value_error exception will be thrown.

Examples

Use the below snippet to find the index of an element 5 in the entire list.

Snippet

list = [1,5,7,9,23,56]

list.index(5)

Where, 5 is existing in the second position in the list. Since the index is 0 based, you’ll see the output as 1.

Output

1

Now, you’ll use the start position and end position to find the index of an element in the specified range.

Use the below snippet which includes the Start position and End position along with the element to find.

Snippet

list = [1,5,7,9,23,56]

list.index(23, 3,5)

Where,

  • 23 – Element to find.
  • 3 – Starting position in the list to find the element
  • 5 – End position in the list to find the element.

Element 23 is available in the list and its index is 4. Hence you’ll see the below output.

Output

4

This is how you can find the index of an element in the list.

Next, you’ll learn the different methods available to find the index of an item.

Find Index Of Item Without Exception

In this section, you’ll learn how to find the index of an item without exception.

You can use this when you want to find the index of Item If Exists. Otherwise, return a default value.

The index() method throws the ValueError if the item doesn’t exist in the list.

Hence, you can catch the ValueError Exception and return a default value in case of the ValueError.

For example, you can return -1 if the value is not found.

Snippet

list = [1,5,7,9,23,56]

try:
    index_value = list.index(20)
except ValueError:
    index_value = -1

print(index_value)    

In the example list, value 20 is not available.

Hence a ValueError will be thrown. Then the exception will be caught and the value -1 will be set to the index_value variable.

Output

 -1

This is how you can find the index of an item in the list without exception.

Next, you’ll find an index of multiple elements.

Find Index Of Multiple Elements

In this section, you’ll learn how to find the index of multiple elements at once.

You’ll use the where() method in NumPy package to find the index and isin() method to pass multiple items.

Snippet

import numpy as np

list = [1,5,7,9,23,56]

idx=np.where(np.isin(list, [5,7]))

idx

Where,

  • np.isin(list, [5,7]) – To find index of 5 and 7 in list object. It’ll return an array with true in the place of the items being searched and false in other indices.
  • np.where() – will use the the booleans in the array to return the indexes.

In the list, 5 and 7 exists in the second and third positions respectively. Hence you’ll see an array as [1,2] as shown below.

Output

(array([1, 2], dtype=int32),)

This is how you can find the index of multiple items.

Next, you’ll learn how to find the index of an item in a NumPy array.

Find Index of Item Using Numpy

In this section, you’ll find the index of an element in the Numpy array.

First, you’ll create an array using np.array().

Then you’ll use the where() method available in the Numpy to find the index of an item.

Snippet

import numpy as np

list = np.array([1,5,7,9,23,56])

item_index = np.where(list == 5)

item_index

Where,

  • list = np.array([1,5,7,9,23,56]) – Creating a Numpy Array
  • np.where(list == 5) – List is the source array name and 5 is the item to find the index.
  • item_index -To print the index of the item

5 is existing in the second position in the numpy array.

Since the index is 0 based, you’ll see the output as array([1]) as shown below.

Output

(array([1], dtype=int32),)

This is how you can find the index of an element in the numpy array.

Next, you’ll find the index of items in the list with a specific conditions.

Find Index Of Item in List with specific condition

In this section, you’ll find the index of items in the list with the specific conditions using list comprehension.

For example, if you need to find the index of items that is greater than 10, you can use list comprehension.

The list comprehension will return a list of index of items that passes the condition.

Snippet

The following code explains how to find the index of items that is greater than 10.

list = [1,5,7,9,23,56]

output = [idx for idx, value in enumerate(list)  if value > 10]

output

Where,

  • idx – To return the index during each iteration if the condition is true.
  • for idx, value in enumerate(list) – To enumerate the list as index and value
  • if value > 10 – To check the value condition during each iteration

The values 23 and 56 are greater than 10 and it is available in the index 4 and 5.

Hence, you’ll see the below output.

Output

[4, 5]

This is how you can find the index of items using list comprehension based on the specific conditions.

Next, Find the index of an item in a case insensitive way.

Find Index Of Item In List Case Insensitive

In this section, you’ll learn how to find the index of an item in a list in a case-insensitive way.

You need to convert the complete list to either lower case or upper case and use the index() method.

Snippet

In the example, you’ll convert the items in the list to lower case using the lower() method and create a new list with the lower case items.

Then you can invoke the index() method in the new list which has lower case items.

to_find = 'b'

list =  ['A', 'B', 'C', 'D', 'E', 'F', 'g', 'h']

lower_list = [item.lower() for item in list]

lower_list.index(to_find.lower())

The lower_list will contain the items in the lower case.

B is available in the second position as b. Since the index is 0 based, you’ll see the output 1.

Output

1

This is how you can find an index in the list using case insensitive way.

Next, you’ll learn about regex.

Find Index Of Item In List Using Regex

In this section, you’ll learn how to find Index Of Match items in the list using regex.

Regex module provides regular expression matching operations to match a string based on the condition.

First, you need to import the regex module using the below statement.

import re

Then you can search for an item using the re.search(expression, item) where,

  • Expression – Condition to pattern match
  • item – Item which needs to be checked if its matching the expression.

To learn more about the regular expression, refer to this regex cheat sheet.

Snippet

The following code explains how to find the index of items that end with a.

import re

countries = ['India', 'United States', 'Canada', 'Germany']

country_idx = [i for i, item in enumerate(countries) if re.search('a$', item)]

country_idx

In the sample list, there are two items India and Canada which ends with a available in position 1 and 3.

Since the Index is 0 based, you’ll see the below output.

Output

[0, 2]

This is how you can find the index of an element using regular expression.

Next, you’ll see about the duplicate elements.

Find Index Of Duplicate Elements

In this section, you’ll find the index of duplicate elements in the list.

You’ll use the packages numpy and pandas for this purpose.

First, you’ll create a dataframe with the list of values and identify the duplicate values using the duplicated() method in the dataframe.

Then, you’ll use the np.where() to identify the index of the duplicate elements.

Snippet

import numpy as np
import pandas as pd

list =  ['a', 'a', 'c', 'f', 'e', 'f', 'g', 'h']

idx = np.where(pd.DataFrame(list).duplicated())

idx

In the sample list, duplicate elements a and f exists in position 2 and 6. Since the index is 0-based, you’ll see the below output.

Output

(array([1, 5], dtype=int32),)

This is how you can find the index of duplicate elements.

Conclusion

To summarize, you’ve learned how to find the index of an item in the list.

You’ve used the index() method to find the index and also used the packages numpy and pandas, where it can be helpful to find the index of an item in various scenarios without any complex code.

You’ve also learned about using the regular expressions and list comprehensions to find the index of an element in the list and find the index of all occurrences of an element in the list.

If you have any questions, comment below.

You May Also Like

Leave a Comment