Python - Find the indices for k Smallest elements
Last Updated :
05 May, 2023
Sometimes, while working with Python lists, we can have a problem in which we wish to find the indices for K smallest elements. This task can occur in many domains such as web development and while working with Databases. We might sometimes, require to just find the indices of them. Let’s discuss a certain way to find indices of K smallest elements in list.
Method 1: Using sorted() + lambda + list slicing
This task can be performed using a combination of the above functions. In this the sorted(), can be used to get the container in a way that requires to get K smallest elements at front end and then the indices can be computed using list slicing.
Python3
# Python3 code to demonstrate working of
# Smallest K elements indices
# using sorted() + lambda + list slicing
# Initialize list
test_list = [5, 6, 10, 4, 7, 1, 19]
# Printing original list
print("The original list is : " + str(test_list))
# initialize K
K = 3
# Smallest K elements indices
# using sorted() + lambda + list slicing
res = sorted(range(len(test_list)), key=lambda sub: test_list[sub])[:K]
# Printing result
print("Indices list of min K elements is : " + str(res))
Output : The original list is : [5, 6, 10, 4, 7, 1, 19]
Indices list of min K elements is : [5, 3, 0]
Time complexity: O(nlogn) (sorting using sorted() function)
Auxiliary space: O(n) (creating a sorted list of indices)
Method 2: using the heapq module
In this method to obtain the indices of the smallest K elements in a list can be to use the heapq module in Python. The heapq module provides the implementation of heap queue algorithm. We can use the nsmallest() function from the heapq module to find the smallest K elements and their indices in a list.
Python3
import heapq
# Initialize list
test_list = [5, 6, 10, 4, 7, 1, 19]
# Printing original list
print("The original list is : " + str(test_list))
# Initialize K
K = 3
# Smallest K elements indices using heapq module
smallest_indices = heapq.nsmallest(
K, range(len(test_list)), key=test_list.__getitem__)
# Printing result
print("Indices list of min K elements is : " + str(smallest_indices))
OutputThe original list is : [5, 6, 10, 4, 7, 1, 19]
Indices list of min K elements is : [5, 3, 0]
Time complexity: O(n log K) where n is the length of the list test list and K is the number of smallest elements required.
Auxiliary space: O(K), which is the size of the heap that is created by the heapq nsmallest() function to store the smallest K elements.
Method 3: Using numpy.argsort() function
The algorithm used in this approach is the argsort function of the NumPy library. The argsort function returns the indices that would sort the input array in ascending order. We pass the input list to the argsort function to obtain an array of indices in ascending order.
Python3
import numpy as np
# Input list
test_list = [5, 6, 10, 4, 7, 1, 19]
# Printing original list
print("The original list is : " + str(test_list))
# Initialize K
K = 3
# Smallest K elements indices
# using numpy.argsort() function
res = np.argsort(test_list)[:K]
# Printing result
print("Indices list of min K elements is : " + str(list(res)))
OutputThe original list is : [5, 6, 10, 4, 7, 1, 19]
Indices list of min K elements is : [5, 3, 0]
Time complexity: O(n log n), where n is the length of the input list. This is because the argsort function uses the quicksort algorithm to sort the input list, which has an average time complexity of O(n log n).
Auxiliary space: O(N), as we are creating a new array to store the sorted indices.
Method 4: Using the bisect module:
Steps:
- Initialize a list test_list with some values and a variable K to a desired value.
- Create a list of indices indices using the range function and the length of the test_list.
- Sort the indices list based on the values in the test_list, using the sort method and a lambda function that takes an 4.index 'i' and returns the corresponding value in test_list[i].
- Take the first K indices from the sorted list to get the smallest_indices.
- Print the original list and the resulting smallest_indices list.
Python3
import bisect
# Input list and value
test_list = [5, 6, 10, 4, 7, 1, 19]
K = 3
# printing original list
print("The original list is : " + str(test_list))
# Creating a list of indices
indices = list(range(len(test_list)))
# Sorting indices based on values of test_list
indices.sort(key=lambda i: test_list[i])
# Getting the first K indices from the sorted list
smallest_indices = indices[:K]
# printing result
print("Indices list of min K elements is : " + str(smallest_indices))
# This code is contributed by Vinay pinjala
OutputThe original list is : [5, 6, 10, 4, 7, 1, 19]
Indices list of min K elements is : [5, 3, 0]
Time complexity: O(n log n), where n is the length of the input list test_list. This is because the algorithm involves sorting the list of indices using the sort() method, which has a time complexity of O(n log n) in the average and worst case.
Auxiliary space: O(n) because it creates a list of indices of length n and a list of K smallest indices, which has a maximum length of K. Therefore, the overall space complexity is dominated by the list of indices of length n.
Method 5 : Using extend(),sort() and index() methods
Approach
- Create a new list with same elements of test_list using extend() method.
- Sort that list using sort() function.
- Slice the list till K index.
- Initiate a for loop to traverse sliced list and append index of element of sliced list in original list to an output list.
- Display output list.
Python3
# Python3 code to demonstrate working of
# Smallest K elements indices
# Initialize list
test_list = [5, 6, 10, 4, 7, 1, 19]
# Printing original list
print("The original list is : " + str(test_list))
# Initialize K
K = 3
# Smallest K elements indices
res = []
x = []
x.extend(test_list)
x.sort()
for i in x[:K]:
res.append(test_list.index(i))
# printing result
print("Indices list of min K elements is : " + str(res))
OutputThe original list is : [5, 6, 10, 4, 7, 1, 19]
Indices list of min K elements is : [5, 3, 0]
Time complexity: O(n log n), where n is the length of the input list test_list. This is because the algorithm involves sorting the list of indices using the sort() method, which has a time complexity of O(n log n) in the average and worst case.
Auxiliary space: O(n) because it creates a list of indices of length n and a list of K smallest indices, which has a maximum length of K. Therefore, the overall space complexity is dominated by the list of indices of length n.
Method 6: Using loop
Steps:
- Initialize the list, test_list, and print it.
- Initialize the value of K and print it.
- Initialize an empty dictionary, index_dict, to store the indices and their corresponding values from test_list.
- Use a for loop to iterate through test_list, and add each element and its index to index_dict.
- Sort the dictionary index_dict by its values, which represent the elements of test_list.
- Create a list, smallest_indices, to store the indices of the smallest K elements.
- Use a for loop to iterate through the sorted index_dict and append the indices of the smallest K elements to the smallest_indices.
- Print the list of indices of the smallest K elements.
Python3
# Initialize list
test_list = [5, 6, 10, 4, 7, 1, 19]
# Printing original list
print("The original list is : " + str(test_list))
# Initialize K
K = 3
# Initializing dictionary to store indices and their corresponding values
index_dict = {}
# Adding each element and its index to the dictionary
for i, value in enumerate(test_list):
index_dict[i] = value
# Sort the dictionary by its values (the elements of test_list)
sorted_dict = dict(sorted(index_dict.items(), key=lambda x: x[1]))
# Create a list to store the indices of the smallest K elements
smallest_indices = []
# Append the indices of the smallest K elements to the list
for i in range(K):
smallest_indices.append(list(sorted_dict.keys())[i])
# Printing result
print("Indices list of min K elements is : " + str(smallest_indices))
OutputThe original list is : [5, 6, 10, 4, 7, 1, 19]
Indices list of min K elements is : [5, 3, 0]
Time complexity: O(nlogn), where n is the length of test_list.
Auxiliary space: O(n) to store the dictionary index_dict and the sorted dictionary sorted_dict
Similar Reads
Python - Elements with same index
Given a List, get all elements that are at their index value. Input : test_list = [3, 1, 8, 5, 4, 10, 6, 9]Â Output : [1, 4, 6]Â Explanation : These elements are at same position as its number.Input : test_list = [3, 10, 8, 5, 14, 10, 16, 9]Â Output : []Â Explanation : No number at its index. Method
5 min read
Element indices Summation - Python
Our task is to calculate the sum of elements at specific indices in a list. This means selecting elements at specific positions and computing their sum. Given a list and a set of indices, the goal is to compute the sum of elements present at those indices. For example, given the list [10, 20, 30, 40
3 min read
Python - Element Index in Range Tuples
Sometimes, while working with Python data, we can have a problem in which we need to find the element position in continuous equi ranged tuples in list. This problem has applications in many domains including day-day programming and competitive programming. Let's discuss certain ways in which this t
7 min read
Python | Get the Index of first element greater than K
Python list operations are always desired to have shorthands as they are used in many places in development. Hence having knowledge of them always remains quite useful. Let's deals with finding one such utility of having index of first element greater than K by one-liner. There are various ways in w
6 min read
Python - Smallest K values in Dictionary
Many times while working with Python dictionary, we can have a particular problem to find the K minima of values in numerous keys. This problem is quite common while working with web development domain. Letâs discuss several ways in which this task can be performed. Smallest K values in Dictionary u
4 min read
Python - Smallest missing element after K
Given a List, get the smallest missing element after K in List. Input : test_list = [1, 3, 4, 5, 7, 9, 10], K = 5 Output : 6 Explanation : After 5, 6 is 1st element missing in list. Input : test_list = [1, 3, 4, 5, 7, 9, 11], K = 9 Output : 10 Explanation : After 9, 10 is 1st element missing in list
6 min read
Python - Indices of atmost K elements in list
Many times we might have problem in which we need to find indices rather than the actual numbers and more often, the result is conditioned. First approach coming to mind can be a simple index function and get indices less than or equal than particular number, but this approach fails in case of dupli
7 min read
Python - K Maximum elements with Index in List
GIven a List, extract K Maximum elements with their indices. Input : test_list = [5, 3, 1, 4, 7, 8, 2], K = 2 Output : [(4, 7), (5, 8)] Explanation : 8 is maximum on index 5, 7 on 4th. Input : test_list = [5, 3, 1, 4, 7, 10, 2], K = 1 Output : [(5, 10)] Explanation : 10 is maximum on index 5. Method
4 min read
Python - Index Ranks of Elements
Given a list of elements, our task is to get the index ranks of each element. Index Rank of Number = (Sum of occurrence indices of number) / number Input : test_list = [3, 4, 6, 5, 3, 4, 9, 1, 2, 1, 8, 3, 2, 3, 9] Output : [(1, 16.0), (2, 10.0), (3, 9.333333333333334), (4, 1.5), (5, 0.6), (6, 0.3333
3 min read
Find Index of Element in Array - Python
In Python, arrays are used to store multiple values in a single variable, similar to lists but they offer a more compact and efficient way to store data when we need to handle homogeneous data types . While lists are flexible, arrays are ideal when we want better memory efficiency or need to perform
2 min read