takachanbo
takachanbo

Reputation: 683

Built in function all() and any() in Python

I'm having trouble with the built-in functions of all(). The code below should print 'fail' but instead gives me a 'success'. Could anyone tell me why this happens?

test = np.array([9.,-1.,2.,3.,5.])

if test[:].all() > 0.:
    print 'success'
else:
    print 'fail'

Upvotes: 0

Views: 234

Answers (1)

BlivetWidget
BlivetWidget

Reputation: 11073

As others mentioned in comments, all() is a boolean function, so it's just looking if all elements are not 0 (aka False).

This is how you want to be using all() for your specific case. It uses a generator comprehension to make an iterable of True and False based on the original array. It will return False if any element is less than or equal to zero.

all(i > 0 for i in test)

Upvotes: 4

Related Questions