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?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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):
Method 2
Use any().
if any(t < 0 for t in x):
# do something
Method 3
Python has a built in any() function for exactly this purpose.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0