471,317 Members | 2,606 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,317 software developers and data experts.

checking for negative values in a list

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
Dec 17 '07 #1
3 23946
On Mon, 17 Dec 2007 06:20:23 -0800, vimal wrote:
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
Dec 17 '07 #2
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
Dec 17 '07 #3
thanks for your help Tim and Marc.
:)
Dec 17 '07 #4

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

7 posts views Thread by Colin Brown | last post: by
19 posts views Thread by David Abrahams | last post: by
26 posts views Thread by Sterten | last post: by
3 posts views Thread by iler.ml | last post: by
39 posts views Thread by Frederick Gotham | last post: by
1 post views Thread by JJ | last post: by
20 posts views Thread by Casey | last post: by
reply views Thread by Gabriel Genellina | last post: by
reply views Thread by rosydwin | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.