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
>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