Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python - Indices of Atmost K Elements in List
Finding indices of elements that are at most K means locating positions of elements that are less than or equal to a given value K. Python provides several approaches using built-in functions like enumerate(), filter(), and NumPy functions.
Problem Statement
Given a list [10, 8, 13, 29, 7, 40, 91] and K value of 13, we need to find indices of elements ? 13. The elements [10, 8, 13, 7] are at positions [0, 1, 2, 4].
Using List Comprehension
List comprehension with enumerate() provides a clean solution ?
k = 10
numbers = [10, 4, 11, 12, 14]
indices = [i for i, num in enumerate(numbers) if num <= k]
print("Indices of elements ?", k, ":", indices)
print("Elements:", [numbers[i] for i in indices])
Indices of elements ? 10 : [0, 1] Elements: [10, 4]
Using Loop and Append
Traditional approach using a for loop ?
k = 40
numbers = [10, 20, 50, 60, 30, 80, 90]
indices = []
for i in range(len(numbers)):
if numbers[i] <= k:
indices.append(i)
print("Indices of elements ?", k, ":", indices)
print("Elements:", [numbers[i] for i in indices])
Indices of elements ? 40 : [0, 1, 4] Elements: [10, 20, 30]
Using NumPy
NumPy's where() function efficiently handles array operations ?
import numpy as np
k = 12
numbers = [10, 4, 11, 12, 14]
arr = np.array(numbers)
indices = np.where(arr <= k)[0]
print("Indices of elements ?", k, ":", indices)
print("Elements:", arr[indices])
Indices of elements ? 12 : [0 1 2 3] Elements: [10 4 11 12]
Using enumerate() and filter()
Functional programming approach using filter() and lambda ?
k = 8
numbers = [10, 4, 11, 12, 14, 1, 2, 89, 0]
indices = list(map(lambda x: x[0], filter(lambda x: x[1] <= k, enumerate(numbers))))
print("Indices of elements ?", k, ":", indices)
print("Elements:", [numbers[i] for i in indices])
Indices of elements ? 8 : [1, 5, 6, 8] Elements: [4, 1, 2, 0]
Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
| List Comprehension | High | Good | Small to medium lists |
| Loop + Append | High | Moderate | Beginners, clear logic |
| NumPy | Medium | Excellent | Large arrays, numerical data |
| Filter + Lambda | Low | Moderate | Functional programming |
Conclusion
Use list comprehension for readable and efficient code. For large datasets, NumPy provides the best performance. The traditional loop approach is most beginner-friendly and easy to debug.
