Python- Find the indices for k Smallest Elements


The indices are the position of the elements present in the list whereas K defines the specific value to target the smallest element from the list. Sometimes, we are working in the field of web development and database these tasks generally occur to solve this problem statement. In Python, we have built-in functions like sorted(), range(), len(), etc. that will be used to find the indices for k Smallest elements.

Syntax

The following syntax is used in the examples-

sorted() 

The sorted() is an in-built function in Python that helps to return the new sorted list while leaving the original list unchanged.

len()

The len() is a built-in method in Python that returns the length of the object.

range()

The range() is a built-in method in Python that is used to return the sequence of elements. The range starts by default 0 and stops before the specified number.

heapq.nsmallest()

The nsmallest() is an in-built function in Python that follows the heapify module to return the smallest number from the list.

argsort()

The built-in function argsort() follows the module name numpy which indirectly sorts the array.

get()

The get() is the built-in method in Python that returns the element value with a specified key.

extend()

extend() is Python built-in function. It iterates over the specified iterable and appends its elements to the end of the current list.

Using a Sorted list and list Comprehension

In the following example, we will use the recursive function that accepts the parameters- input list and k value. The k value set to 3 means it sorts the first three elements from the lists. Then using some built-in functions such as sorted(), len(), and, lambda will calculate the indices for k smallest element. Next, using the slicing notation of K it returns the desired result.

Example

def k_smallest_indices(lst, k):
    sorted_indices = sorted(range(len(lst)), key=lambda i: lst[i])
    return sorted_indices[:k]
# Create the list
list_1 = [50, 20, 90, 10, 70]
# k variable sort the first three elements from the list
k = 3 
small_indices = k_smallest_indices(list_1, k)
print("The smallest elements are-",small_indices)

Output

 The smallest elements are- [3, 1, 0]

Using heapq and heap Data Structure

In the following example, we will start the program by defining the module named heapq that will be used to find the K smallest elements. Then using the recursive function it receives two parameters value- input list and k value that work on built-in function nsmallest() and list comprehension to store in the respective variable. Next, using a function return generates the specified result.

Example

import heapq
def find_k_smallest_indices(lst, k):
    smallest_elements = heapq.nsmallest(k, lst)
    smallest_indices = [i for i, val in enumerate(lst) if val in smallest_elements]
    return smallest_indices
# create the list
my_list = [5, 4, 3, 2, 1]
k = 3
smallest_indices = find_k_smallest_indices(my_list, k)
print("The smallest index elements are-",smallest_indices)

Output

The smallest elements are- [2, 3, 4]

Using numpy.argsort()

In the following example, we will use the numpy library that provides the built-in function argsort() to sort the input list element. The program uses a recursive function that reduces the time complexity of the program. It accepts two parameters- input list and k value to find the K smallest element. The K sets to a specific number which represents the total count of indices that prints the result according to the given value. Moving ahead to use the function return with slicing notation to get the output of the program.

Example

import numpy as np
def find_k_smallest_indices(lst, k):
    indices = np.argsort(lst)
    return indices[:k]
# Create the list
my_list = [55, 7, 12, 2, 67, 90, 9]
# Initialize the k value
k = 3
smallest_indices = find_k_smallest_indices(my_list, k)
print("The smallest index elements are-", smallest_indices)

Output

 The smallest index elements are- [3 1 6]

Using a loop and a Dictionary

In the following example, the program uses two for-loop for the iteration of the input list by using some built-in functions such as enumerate(), get(), and, extend() to find the indices for K smallest elements.

Example

def find_k_smallest_indices(lst, k):
    indices = {}
    for i, val in enumerate(lst):
        indices[val] = indices.get(val, []) + [i]
    sorted_indices = []
    for val in sorted(lst)[:k]:
        sorted_indices.extend(indices[val])
    return sorted_indices
# Create the list
my_list = [5, 2, 9, 1, 7]
k = 3
smallest_indices = find_k_smallest_indices(my_list, k)
print("The smallest index elements are-", smallest_indices)

Output

 The smallest index elements are- [3, 1, 0]

Conclusion

We discussed the solution of indices of K smallest elements by using various methods. The heapq module is the new approach that defines the heap data structure to solve this problem. In some of the examples, the slicing notation will be used to specify the exact index positioning based on conditions and operations.

Updated on: 16-Aug-2023

111 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements