5 Best Ways to Find Python Indices of Numbers Greater Than k

πŸ’‘ Problem Formulation: You have a list of integers and a number k. Your task is to find the indices of all numbers in the list that are greater than k. For instance, given the list [1, 5, 7, 3, 8] and k as 4, the desired output would be the indices [1, 2, 4].

Method 1: Using a for-loop and list append

This approach involves iterating over the list with a for-loop and appending the index of each element that is greater than k to a new list. It’s straightforward and easy to understand for those new to Python.

Here’s an example:

def find_indices(lst, k):
    indices = []
    for i, num in enumerate(lst):
        if num > k:
            indices.append(i)
    return indices

# Example usage
indices = find_indices([9, 2, 6, 3, 5], 3)

Output:

[0, 2, 4]

This code snippet defines a function find_indices(lst, k) that returns a new list of indices. It uses enumerate() to get both the index and the value for elements in the original list, making it easy to tell if a number is greater than k and then capture its index.

Method 2: Using list comprehensions

List comprehensions provide a concise way to create lists. They are typically more compact and faster than normal for-loops because they are optimized for Python’s interpreter.

Here’s an example:

lst = [10, 12, 3, 5, 17]
k = 8
indices = [i for i, n in enumerate(lst) if n > k]

Output:

[1, 4]

The list comprehension iterates over lst using enumerate() to retrieve both the index and number. The if condition filters out those numbers not greater than k, resulting in a list of appropriate indices.

Method 3: Using the filter and lambda functions

This method combines filter() with a lambda function to isolate the indices of elements greater than k. While not as readable as list comprehensions, it can be useful for larger datasets.

Here’s an example:

lst = [4, 18, 10, 5, 6]
k = 7
indices = list(filter(lambda i: lst[i] > k, range(len(lst))))

Output:

[1, 2]

The lambda function takes an index and returns true if the corresponding list element is greater than k. filter() applies this lambda to every index and filters in those that meet the condition.

Method 4: Using NumPy arrays

For numerically intensive computing, NumPy provides efficient storage and manipulation of arrays. Using NumPy, you can filter indices quickly, especially when working with large datasets.

Here’s an example:

import numpy as np

arr = np.array([2, 3, 15, 7, 9])
k = 6
indices = np.where(arr > k)[0]

Output:

[2, 4]

The code example uses NumPy’s np.where() function to find indices where the condition is true. This function is highly optimized and can be significantly faster than Python loops for large arrays.

Bonus One-Liner Method 5: Using itertools.compress

The itertools.compress function offers another way to filter list indices based on a condition. It can lead to very compact code but sacrificing some readability for those unfamiliar with itertools.

Here’s an example:

from itertools import compress

lst = [6, 7, 10, 2, 5]
k = 5
indices = list(compress(range(len(lst)), (n > k for n in lst)))

Output:

[1, 2]

itertools.compress accepts two iterators: the first one is the list of indices, and the second is a generator expression that evaluates the condition for each element. It returns only those indices for which the condition is True.

Summary/Discussion

  • Method 1: For-loop and list append. Easy for beginners to understand. Can be slow for large lists.
  • Method 2: List comprehensions. Concise and Pythonic. Faster than for-loops but may consume more memory.
  • Method 3: Filter with lambda. Good for large lists. Less readable than list comprehensions.
  • Method 4: Using NumPy arrays. Best for numerical computations and large datasets. Requires an external library.
  • Method 5: Using itertools.compress. Compact code for one-liners. Not as intuitive for those new to Python’s itertools.