Jonathan
Jonathan

Reputation: 641

How to return the index of the first non-negative list in a list of lists in Python?

The desired output is the index of the first non-negative list.

Say I nested list of numbers like below. I am trying to figure out how to remove the values of the negative lists or just return the index where all the values in the list are positive.

My idea was to enumerate or loop a function that checks if a list has a negative value then pop or remove from the list of lists

Or do I use a list comprehension?

# pseudocode
x = [[-1, -2, -1], [-1, -3, -1], [1, 2, 2]]
index_x = [x.index(non_negative(x)) for x in data]
print(index_x)
# 2 

Upvotes: 2

Views: 732

Answers (3)

ninesalt
ninesalt

Reputation: 4354

Why not do something like this? Just iterate through the lists.

from functools import reduce

x = [[-1, -2, -1], [-1, -3, -1], [1, 2, 2]]

for index, sublist in enumerate(x):
    if reduce(lambda a, b: a >= 0 and b >= 0, sublist):
        print(index)
        break

Upvotes: 0

millimoose
millimoose

Reputation: 39950

For this I'd just use a function with an early return, which I feel makes the intent of "stop looking when you find this" clearer:

def first_non_negative(lsts):
    for idx, lst in enumerate(lsts):
        if all(it > 0 for it in lst): 
            return idx

Upvotes: 0

jpp
jpp

Reputation: 164623

You can use next with a generator expression and enumerate + all. Your logic is equivalent to finding the index of the first sublist containing all non-negative values.

x = [[-1, -2, -1], [-1, -3, -1], [1, 2, 2]]

res = next((idx for idx, sub in enumerate(x) if all(i >= 0 for i in sub)), None)

# 2

A list comprehension is only useful if you wish to extract indices for all sublists matching a condition. The built-in next function retrieves the first value from an iterable. If no sublist is found, the specified None will be returned.

Upvotes: 5

Related Questions