checking for negative values in a list

Tim Chase python.list at tim.thechases.com
Mon Dec 17 09:45:58 EST 2007


>     i am new to python guys.
>    i have a list of numbers
> 
>   say a = [1,-1,3,-2,4,-6]
> 
>   how should i check for negative values in the list

I'm not sure if this is a homework problem, as it seems to be a 
fairly simple programming problem whether you know Python or not.

If you're using 2.5 or more recent, you should be able to do 
something like

   if any(x < 0 for x in a):
     yep()
   else:
     nope()

If "a" is small, you could do

   if [x for x in a if x < 0]:
     yep()
   else:
     nope()

Or you could write your own function:

   def has_negatives(iterable):
     for x in iterable:
       if x < 0: return True
     return False

   if has_negatives(a):
     yep()
   else:
     nope()

-tkc





More information about the Python-list mailing list