Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python equivalent of Scala's exists() function?

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?

like image 781
Rex Avatar asked Sep 11 '26 22:09

Rex


1 Answers

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
like image 88
Peter Wood Avatar answered Sep 13 '26 14:09

Peter Wood