0

how do you detect if a value held in a list is negative, I just need to find out if there is a value that is negative, so far i have this:

if list[range(list)] < 0

But surely this will only detect if all the values in list are negative.How would i go about doing this?

Also, how would i be able to detect if a value in the list was not an integer, for example it was a floating point number, or even a character

Thanks

SammyHD
  • 49
  • 2
  • 8

1 Answers1

8

You can use any function, like this

if any(item < 0 for item in my_list):

For example,

print any(item < 0 for item in [0, 1, 2])
# False
print any(item < 0 for item in [0, 1, -2])
# True

We use a generator expression in the any function. It returns True, if any of the item is lesser than 0.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
  • Out of curiosity, does `any` stop once it hits the first `True` element? If not, if the list was very long, I wonder if it would be worth manually looping through, and breaking on the first True, since at that point there is no need to check the remaining elements. Just thinking out loud. – Cory Kramer Apr 14 '14 at 12:26
  • @Cyber Exactly. It returns immediately after getting `True`. – thefourtheye Apr 14 '14 at 12:26