Open In App

Python | Ways to find indices of value in list

Last Updated : 18 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Usually, we require to find the index, in which the particular value is located. There are many methods to achieve that, using index(), etc. But sometimes require to find all the indices of a particular value in case it has multiple occurrences in the list. Let’s discuss certain ways to find indices of value in the given list of Python.

Ways to find indices of value in the list

Below are the methods that we will cover in this article:

Find the Index of an Item Using the Naive Method

We can achieve this task by iterating through the list and checking for that value and just appending the value index in a new list and printing that. This is the basic brute force method to achieve this task.

Python3




# initializing list
test_list = [1, 3, 4, 3, 6, 7]
 
# printing initial list
print("Original list : " + str(test_list))
 
# using naive method to find indices for 3
res_list = []
for i in range(0, len(test_list)):
    if test_list[i] == 3:
        res_list.append(i)
 
 
# printing resultant list
print("New indices list : " + str(res_list))


Output

Original list : [1, 3, 4, 3, 6, 7]
New indices list : [1, 3]

Time Complexity: O(n)
Auxiliary Space: O(n)

Find the Index of an Item Using List Comprehension

List comprehension is just the shorthand technique to achieve the brute force task, just uses lesser lines of codes to achieve the task and hence saves programmers time.

Python3




# initializing list
test_list = [1, 3, 4, 3, 6, 7]
 
# printing initial list
print("Original list : " + str(test_list))
 
# using list comprehension
# to find indices for 3
res_list = [i for i in range(len(test_list)) if test_list[i] == 3]
 
# printing resultant list
print("New indices list : " + str(res_list))


Output

Original list : [1, 3, 4, 3, 6, 7]
New indices list : [1, 3]

Time Complexity: O(n)
Auxiliary Space: O(n)

Find the Index of an Item Using Enumerate() Function 

Using enumerate() we can achieve a similar task, this is a slightly faster technique than above and hence is recommended to be used over the list comprehension technique.

Python3




# initializing list
test_list = [1, 3, 4, 3, 6, 7]
 
# printing initial list
print("Original list : " + str(test_list))
 
# using enumerate()
# to find indices for 3
res_list = [i for i, value in enumerate(test_list) if value == 3]
 
# printing resultant list
print("New indices list : " + str(res_list))


Output

Original list : [1, 3, 4, 3, 6, 7]
New indices list : [1, 3]

Time Complexity: O(n)
Auxiliary Space: O(n)

Find the Index of an Item Using filter() Function 

This is yet another method that can be employed to achieve this particular task, filter() usually is able to perform the filtering tasks and hence can also be used in this situation to achieve this task. 

Python3




# initializing list
test_list = [1, 3, 4, 3, 6, 7]
 
# printing initial list
print("Original list : " + str(test_list))
 
# using filter() to find indices for 3
res_list = list(filter(lambda x: test_list[x] == 3, range(len(test_list))))
 
# printing resultant list
print("New indices list : " + str(res_list))


Output

Original list : [1, 3, 4, 3, 6, 7]
New indices list : [1, 3]

Time Complexity: O(n)
Auxiliary Space: O(n)

Find the Index of an Item Using numpy Library

This program uses the numpy library to convert a given list into an array, finds the indices of the given value in the array, and converts the resulting numpy array back to a list. Finally, it prints the list of indices.

Python3




import numpy as np
 
test_list = [1, 3, 4, 3, 6, 7]
 
# convert the list to a numpy array
test_array = np.array(test_list)
 
# find the indices of the value 3 in the array
res_array = np.where(test_array == 3)[0]
 
# convert the numpy array back to a list
res_list = list(res_array)
 
# printing resultant list
print("New indices list : " + str(res_list))


OUTPUT:

New indices list : [1, 3]

Time complexity: O(n), where n is the length of the input list.
Auxiliary space: O(n), because it creates a new numpy array with the same length as the input list.

Find the Index of an Item Using a for Loop

Initialize an empty list called “res_list” to store the indices of the target values.Iterate through each element in the input list “test_list” using a for loop.If the current element matches the target value, append its index to the “res_list”.After the loop is finished, return the “res_list” as the output.

Python3




# initializing list
test_list = [1, 3, 4, 3, 6, 7]
 
# printing initial list
print("Original list: " + str(test_list))
 
# using a for loop to find indices for 3
res_list = []
for i in range(len(test_list)):
    if test_list[i] == 3:
        res_list.append(i)
 
# printing resultant list
print("New indices list: " + str(res_list))


Output

Original list: [1, 3, 4, 3, 6, 7]
New indices list: [1, 3]

Time complexity: O(n), where n is the length of the input list “test_list”.
Auxiliary space: O(k), where k is the number of occurrences of the target value.

Find the Index of an Item Using list.index() Method with a while Loop

Initialize an empty list indexes to store the indices of the given value.Initialize a variable i to -1.Run a while loop that continues until the break statement is encountered.Inside the while loop, use the list.index() method to find the index of the given value in the list starting from index i + 1.If the index is found, append it to the indexes list and update the value of i to the index found.If the index is not found, break the while loop.Print the indexes list.

Python3




# initializing list
my_list = [1, 3, 4, 3, 6, 7]
 
# printing initial list
print("Original list : " + str(my_list))
 
# using list.index() method with a while loop to find indices for 3
indexes = []
i = -1
while True:
    try:
        i = my_list.index(3, i + 1)
        indexes.append(i)
    except ValueError:
        break
 
print("New indices list : " + str(indexes))


Output

Original list : [1, 3, 4, 3, 6, 7]
New indices list : [1, 3]

Time Complexity: O(n),The list.index() method has a time complexity of O(n) in the worst case because it needs to iterate through the list to find the index of the given value.The while loop also has a time complexity of O(n) in the worst case because it needs to iterate through the list to find all occurrences of the given value.
Auxiliary Space: O(1),The space used by the indexes list and i variable is constant and does not depend on the size of the input list, so the auxiliary space complexity is O(1).



Previous Article
Next Article

Similar Reads

NumPy indices() Method | Create Array of Indices
The indices() method returns an array representing the indices of a grid. It computes an array where the subarrays contain index values 0, 1, … varying only along the corresponding axis. Example C/C++ Code import numpy as np gfg = np.indices((2, 3)) print (gfg) Output : [[[0 0 0] [1 1 1]] [[0 1 2] [0 1 2]]]Syntax numpy.indices(dimensions, dtype, sp
2 min read
Python | Indices of sorted list of list elements
Sorting is a common construct and there have been many variations of it being discussed. But sometimes, we need to perform the sorting on the list of list and moreover just require to find the order in which element occurs before getting sorted. Let's find out how to get indices of sorted order in list of lists. Method #1 : Using List comprehension
6 min read
Python | Indices list of matching element from other list
Sometimes, while working with Python list, we have a problem in which we have to search for an element in list. But this can be extended to a list and need to find the exact places where elements occur in another list. Let's discuss certain ways in which this task can be performed. Method #1: Using loop + count() This is the brute method to perform
7 min read
Python program to get the indices of each element of one list in another list
Given 2 lists, get all the indices of all occurrence of each element in list2 from list1. Input : test_list = [4, 5, 3, 7, 8, 3, 2, 4, 3, 5, 8, 3], get_list = [7, 5, 4] Output : [[3], [1, 9], [0, 7]] Explanation : 5 is present at 1st and 9th index. Input : test_list = [4, 5, 3, 7, 8, 3, 2, 4, 3, 5, 8, 3], get_list = [7, 5, 8] Output : [[3], [1, 9],
7 min read
Python | Find indices with None values in given list
Many times while working in data science domain we need to get the list of all the indices which are None, so that they can be easily be prepossessed. This is quite a popular problem and solution to it comes quite handy. Let's discuss certain ways in which this can be done. Method #1 : Using list comprehension + range() In this method we just check
7 min read
Python | Find elements of a list by indices
Given two lists with elements and indices, write a Python program to find elements of list 1 at indices present in list 2. Examples: Input : lst1 = [10, 20, 30, 40, 50] lst2 = [0, 2, 4] Output : [10, 30, 50] Explanation: Output elements at indices 0, 2 and 4 i.e 10, 30 and 50 respectively. Input : lst1 = ['Hello', 'geeks', 'for', 'geeks'] lst2 = [1
5 min read
Python - Find the Maximum of Similar Indices in two list of Tuples
Sometimes, while working with Python records, we can have a problem in which we need to perform cross maximization of list of tuples. This kind of application is popular in web development domain. Let’s discuss certain ways in which this task can be performed. Method #1 : Using list comprehension + zip() The combination of above functionalities can
7 min read
Python Program to find tuple indices from other tuple list
Given Tuples list and search list consisting of tuples to search, our task is to write a Python Program to extract indices of matching tuples. Input : test_list = [(4, 5), (7, 6), (1, 0), (3, 4)], search_tup = [(3, 4), (8, 9), (7, 6), (1, 2)]Output : [3, 1]Explanation : (3, 4) from search list is found on 3rd index on test_list, hence included in r
8 min read
Python | Segregate True and False value indices
Sometimes, while working with Python lists, we can have a problem in which we have boolean list and require to have indices of True and False values separately. This can have a possible use in Data Science domain. Let's discuss certain ways in which this task can be performed. Method #1 : Using loop This is the one way in which this task can be per
6 min read
Python | Indices of Kth element value
Sometimes, while working with records, we might have a problem in which we need to find all the indices of elements for a particular value at a particular Kth position of tuple. This seems to be a peculiar problem but while working with many keys in records, we encounter this problem. Let's discuss certain ways in which this problem can be solved.
4 min read
Practice Tags :