Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

does python have an equivalent to javascript's every and some method?

I was trying to search the docs for a method similar but I was only able to find pythons all() and any(). But that’s not the same because it just checks if the val is truthy instead of creating your own condition like in js’ every and some method.
i.e

// return true if all vals are greater than 1
const arr1 = [2, 3, 6, 10, 4, 23];
console.log(arr1.every(val => val > 1)); // true

// return true if any val is greater than 20
const arr2 = [2, 3, 6, 10, 4, 23];
console.log(arr2.some(val => val > 20)); // true

Is there a similar method that can do this in python?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Just combine it with a mapping construct, in this case, you would typically use a generator expression:

arr1 = [2, 3, 6, 10, 4, 23]
print(all(val > 1 for val in arr1))

arr2 = [2, 3, 6, 10, 4, 23]
print(any(val > 20 for val in arr2))

Generator comprehensions are like list comprehensions, except they create a generator not a list. You could have used a list comprehension, but that would create an unecessary intermediate list. The generator expression will be constant space instead of linear space. See this accepted answer to another question if you want to learn more about these related constructs

Alternatively, albeit I would say less idiomatically, you can use map:

arr1 = [2, 3, 6, 10, 4, 23]
print(all(map(lambda val: val > 1, arr1)))

arr2 = [2, 3, 6, 10, 4, 23]
print(any(map(lambda val: val > 20, arr2)))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading