What is the python equivalent of JavaScript's Array.prototype.find?
Array.prototype.find()
returns the first matching element in an array, given a predicate function, or undefined
when there is no match.
Python has the filter()
function, which filters an iterable on a predicate, and next()
, which produces the first element of an iterable or an optional default. Combining these give you the equivalent:
next(filter(pred, iter), None)
where pred
is a callable that returns True
when an element matches the search criteria.
Demo:
>>> iterable = [42, 81, 117]
>>> parity_odd = lambda v: v % 2 == 1
>>> next(filter(parity_odd, iterable), None)
81
>>> iterable = [42, 2, 4]
>>> next(filter(parity_odd, iterable), None) is None
True
If you remove the second argument to next()
, a StopIteration
exception is raised when there is no matching element.
def find(pred, iterable):
for element in iterable:
if pred(element):
return element
return None
# usage:
find(lambda x: x.get("name") == "bbbb", obj.get("foo_list", []))