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

Question:

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?

Asked By: Ronny Fitzgerald

||

Answers:

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)))
Answered By: juanpa.arrivillaga

Yes, Python has it.

numbers = [1, 2, 3, 4, 5]
all_are_one = all(elem == 1 for elem in numbers)
some_are_one = any(elem == 1 for elem in numbers)
Answered By: Nave Twizer
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.