Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What is the best way to return a boolean when a negative value exists in a list?

I have the following funciton telling us that a series has at least one negative value:

def has_negative(series):
    v=False
    for i in range(len(series)):
        if series[i]<0:
            v=True
            break
    return v

When we use this function on an example we get :

y=[1,2,3,4,5,6,7,8,9]
z=[1,-2,3,4,5,6,7,8,9]

print(has_negative(y))
print(has_negative(y))

Output:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>>> False
>>> True

The function seems to work well, although I want to make it shorter, any suggestion from your side will be appreciated

>Solution :

You can utilise the built-in any function as follows:

def has_negative(lst):
    return any(e < 0 for e in lst)

print(has_negative([1,2,3,4,5,6,7,8,9]))
print(has_negative([1,-2,3,4,5,6,7,8,9]))

Output:

False
True

EDIT:

Did some timing tests based around this and other suggested answers. Whilst this is concise and functionally correct, it doesn’t perform well. Keep it simple and use @quamrana’s first suggestion – it’s much faster

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading