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

Question:

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:

``````>>> False
>>> True
``````

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

There are several improvements you can make:

``````def has_negative(series):
for i in series:
if i < 0:
return True
return False
``````

or it can be contracted into one line like this:

``````print(bool([i for i in z if i<0]))
``````

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

You can sort the list and get the first element, check if it’s a negative. With this approach you don’t have to iterate over the array:

``````sorted(series)[0] < 0
``````

To keep it clean and short, you could also use a list comprehension within a lambda function as follows:

``````has_negative = lambda series: True if [series for x in series if x < 0] else False
``````
``````z = [1,-2,3,4,5,6,7,8,9]

has_negative(z)
``````

Output:

``````>>> True
``````
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.