Does python have any equivalent to JavaScript’s Array.prototype.some / every?
Trivial JavaScript example:
var arr = [ "a", "b", "c" ];
arr.some(function (element, index) {
console.log("index: " + index + ", element: " + element)
if(element === "b"){
return true;
}
});
Will output:
index: 0, element: a index: 1, element: b
The below python seems to be functionally equivalent, but I do not know if there is a more “pythonic” approach.
arr = [ "a", "b", "c" ]
for index, element in enumerate(arr):
print("index: %i, element: %s" % (index, element))
if element == "b":
break
Advertisement
Answer
Python has all(iterable) and any(iterable). So if you make a generator or an iterator that does what you want, you can test it with those functions. For example:
some_is_b = any(x == 'b' for x in ary) all_are_b = all(x == 'b' for x in ary)
They are actually defined in the documentation by their code equivalents. Does this look familiar?
def any(iterable):
for element in iterable:
if element:
return True
return False