0
import numpy as np
y = [1.25, 2.59, -4.87, 6.82, -7.98, -11.23]

if(np.any(y) < -10):
    print("yes")

I want to check whether in a list any value below or above a particular value exists or not. So, I proceed with np.any(), code is getting compiled but not working as wished, I mean not printing back "yes".

4 Answers 4

6

any should be after the brackets, and y should be a numpy array.

import numpy as np
y = np.array([1.25, 2.59, -4.87, 6.82, -7.98, -11.23])

if (y < -10).any():
    print("yes")
Sign up to request clarification or add additional context in comments.

4 Comments

Yes. It has worked. Thanks. However, since I don't know the difference in y= np.array([.....]) and y = [...], could you explain this one !
y=np.array([]) creates a numpy array, while y = [...] creates a list. A list is a built-in data type in python used to store values. A numpy array is from the module numpy and can be used with certain math operations.
if (y < -10).any(2): print("yes"). Would it then be used as "if 2 of the numbers of the array are less than -10 then print yes" ??
No, but you can achieve this with sum: if sum((y < -10))==2: print("yes")
1

np.any() returns a bool and you cannot compare it with an int.

it's like doing true/false < -10

The correct use of np.any() would be as follows:

(y < -10).any()

Comments

1
y = [1.25, 2.59, -4.87, 6.82, -7.98, -11.23]

for value in y:
    if value < -10:
        print(f'yes there is {value} less than -10')

Your Output

yes there is -11.23 less than -10

3 Comments

print(f 'yes there is {value} less than -10') ^ SyntaxError: invalid syntax
it is showing the above mentioned error, could you please help me in sorting this !
yes use print(f'yes there is {value} less than -10'). Sorry there is no space between f string in print. This works perfectly. Thank you for asking Subhadip.
0

This should do the job

import numpy as np
y1 = np.array([1.25, 2.59, -4.87, 6.82, -7.98, -11.23])
y2 = np.array([1.25, 2.59, 4.87, 6.82, 7.98, 11.23])

if(np.any(y1 < -10)):
    print("yes y1")
else:
    print("no y1")

if(np.any(y2 < -10)):
    print("yes y2")
else:
    print("no y2")

Other option will be to not use numpy module, and just to scan the array elements one by one.

2 Comments

Yes.This is also working quite well. Thanks.
Sir, What if I want to check, say, any 2 of the numbers of an array is greater than +5.0 ! Would it be possible using this any() function ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.