checking for negative values in a list

V

vimal

hi all,

i am new to python guys.
hope u will help me with this....

i have a list of numbers

say a = [1,-1,3,-2,4,-6]

how should i check for negative values in the list
 
M

Marc 'BlackJack' Rintsch

i have a list of numbers

say a = [1,-1,3,-2,4,-6]

how should i check for negative values in the list

In [6]: a = [1, -1, 3, -2, 4, -6]

In [7]: any(n < 0 for n in a)
Out[7]: True

Ciao,
Marc 'BlackJack' Rintsch
 
T

Tim Chase

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,534
Members
45,008
Latest member
Rahul737

Latest Threads

Top