Scala lists have an exists() function that returns a boolean if the list has an element that satisfies your predicate.
Is there a way to do this in python that's just as clean?
I've been using
if next(x for x in mylist if x > 10): return Something
Is there a better way?
Use any:
if any(x > 10 for x in mylist):
return Something
You can complement this with all, and use not any and not all to round it out.
Your way of using next will raise an exception if it doesn't find anything. You can pass it an additional default value to return, instead:
if next((x for x in mylist if x > 10), None):
return Something
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With