3 ms·
I wish `any()` returned the first truthy item in an iterable instead of `True`.
by heavyset_go 5y ago
I wish `any()` returned the first truthy item in an iterable instead of `True`.
- mixmastamyk 5y agoSounds like coalesce () from SQL.
- dragonwriter 5y agoSimilar, though a more perfect analog to coalesce() would return the first non-None item.
- pyuser583 5y agoI like.
- JNRowe 5y agoThe itertools documentation¹ include a recipe to do just that, and links to the excellent more-itertools² package which bundles up a heap of recipes that make iterators even better. This specific case is handled by first_true² in more-itertools. ¹ https://docs.python.org/3/library/itertools.html#itertools-recipes https://docs.python.org/3/library/itertools.html#itertools-r... ² https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.first_true https://more-itertools.readthedocs.io/en/stable/api.html#mor...
- memco 5y agoI think the first_true optio is great and I highly recommend more-itertools, but if you’re looking for a built in alternative I usually use next((I for I in iter if is_thing(I)), default) It’s slightly more work than any but is pretty much all I need when I need to handle whatever values are returned from the any.
- deleted 5y ago[deleted]
- deleted 5y ago[deleted]
- Erwin 5y agoYou can now get the first item by abusing the walrus operator, e.g. `any((z := x) for x in [3,5,7] if x % 3)` -- afterwards, z have retained the first assignment for which `x % 3` was true.
- joppy 5y agoIn MAGMA, a computer algebra programming language, there is a “exists” statement which takes a comprehension and evaluates to true if any item is true, something like exists{x % 2 == 0 for x in numbers}. But it also has an extra parameter which can bind the value of the first item satisfying the condition, something like If exists(y){x : x % 2 == 0 for x in numbers}: Print y There is also a “for all” statement which can return the first offender which does not satisfy the condition. It’s an awkward but incredibly useful language choice - it would be interesting to see it explored more in mainstream languages.
- jackdreilly 5y ago`next((x for x in xs if x), False)` is pretty concise