Evan Kim
Evan Kim

Reputation: 829

Check if all elements in nested list are positive or negative in python

I am trying to use a list comprehension to find the nested list whose elements are all positive, but I am not sure how to phrase the conditional to check all the values in the nested list for the list comprehension.

records = [[-167.57, 4.0, 61.875, -100.425],
 [-1.75, 3.75, 4.0],
 [7612.875, 10100.0, 74.25, 1.75, 61.875],
 [-2333.37, -5404.547500000001, -5178.645833333333, 97.0, 167.57],
 [-96.99999999999997, -5277.999999999999, -4998.5, 74.25, 3.75]]

answer = [i for i in records if (n < 0 for n in i)]
answer

I think this is the statement I am trying to turn into code: "if all n > 0 for n in i, return index i"

edit: Output would be to return the index of the corresponding row of all positive numbers

Upvotes: 1

Views: 9633

Answers (3)

cs95
cs95

Reputation: 402493

You are close. Imagine how you would do this in a loop:

for index, row in enumerate(records):
    if all(col > 0 for col in row): 
        print(index)

The if condition with all returns True if all elements are positive only. Now put this into list comprension form:

answer = [
    index 
    for index, row in enumerate(records) 
    if all(col > 0 for col in row)
]
# [2]

List comprehensions are optimized versions of for loops specifically made for creating lists. There is usually a one-to-one translation between a loop generating a list, and a list comprehension. My advice when you are stuck on list comp syntax is to take a step back and visualize what this looks like as a simple for loop. Here are two important rules of optimization (as told to me by my mentor in university):

  1. Don't optimize
  2. Don't optimize yet

Upvotes: 6

azro
azro

Reputation: 54148

You may use the all built-in method that

Return True if all elements of the iterable are true (or if the iterable is empty)

  • for all negative

    answer = [all(n < 0 for n in i) for i in records] # [False, False, False, False, False]
    
  • for all positive

    answer = [all(n > 0 for n in i) for i in records] # [False, False, True, False, False]
    

To get indexes of all-positive rows, combine with enumerate

answer = [idx for idx,row in enumerate(records) if all(n > 0 for n in row)] # [2]

Upvotes: 1

Erich
Erich

Reputation: 1848

You can use all to check whether all elements satisfy a given condition, e.g.

answer = [all(n > 0 for n in lst) for lst in records]

Upvotes: 1

Related Questions