tags:

views:

202

answers:

3

I have a list in Python, and I want to check if any elements are negative. Specman has the has() method for lists which does:

x: list of uint;
if (x.has(it < 0)) {
    // do something
};

Where it is a Specman keyword mapped to each element of the list in turn.

I find this rather elegant. I looked through the Python documentation and couldn't find anything similar. The best I could come up with was:

if (True in [t < 0 for t in x]):
    # do something

I find this rather inelegant. Is there a better way to do this in Python?

+25  A: 

any():

if any(t < 0 for t in x):
    # do something

Also, if you're going to use "True in ...", make it a generator expression so it doesn't take O(n) memory:

if (True in (t < 0 for t in x)):
Ken
Beat me to it by 18 seconds. Yes, `any()` is the correct answer here.
Daniel Pryden
On the simple questions you have to be fast *and* lucky to get da points. :-)
Ken
If it's that simple maybe I should add a *newbie* tag to this :-)
Nathan Fellman
+12  A: 

Use any().

if any(t < 0 for t in x):
    # do something
Daniel Pryden
+1 for having the correct answer, only 18 seconds too late.
Michael Deardeuff
+6  A: 

Python has a built in any() function for exactly this purpose.

Rory
2.5+ only. Otherwise you have to make a function, maybe using ifilter and exceptions, or bool(set((x for x if cond))) or the like.
Gregg Lind