What is the python JavaScript equivalent of Array.prototype.some?

Does python have the JavaScript equivalent of Array.prototype.some / every ?

An example of trivial JavaScript:

var arr = [ "a", "b", "c" ]; arr.some(function (element, index) { console.log("index: " + index + ", element: " + element) if(element === "b"){ return true; } }); 

It will display:

 index: 0, element: a index: 1, element: b 

The following python seems to be functionally equivalent, but I don't 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 
+7
javascript python arrays
source share
2 answers

Python has all(iterable) and any(iterable) . Therefore, if you create a generator or an iterator that does what you want, you can test it using these 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 for their code equivalents. Does this look familiar?

 def any(iterable): for element in iterable: if element: return True return False 
+5
source share

Not. NumPy arrays do , but standard python lists do not. However, the implementation of numpy arrays is not what you expect: they do not take a predicate, but evaluate each element, converting them to logical ones.

Edit : any and all exist as functions (and not as methods), but they do not use predicates, but treat logical values โ€‹โ€‹as numpy methods.

In Python, some might be:

 def some(list_, pred): return bool([i for i in list_ if pred(i)]) #or a more efficient approach, which doesn't build a new list def some(list_, pred): return any(pred(i) for i in list_) #booleanize the values, and pass them to any 

You can implement every :

 def every(list_, pred): return all(pred(i) for i in list_) 

Edit : dumb sample:

 every(['a', 'b', 'c'], lambda e: e == 'b') some(['a', 'b', 'c'], lambda e: e == 'b') 

Try them urself

-one
source share

All Articles