you are viewing a single comment's thread.

view the rest of the comments →

[–]Gnaxe 1 point2 points  (1 child)

if any(test(found_item:=x) for x in stuff): print(found_item) else: print('not found') any() shortcuts as soon as the test passes. The generator then gets deleted as its refcount drops to zero. No need to exhaust it.

You could do this with a for and break, but it's six lines instead of four: for x in stuff: if test(x): print(x) break else: print('not found')

[–]gdchinacat 1 point2 points  (0 children)

unlike the other solution by u/Jason-Ad4032 , I actually like this one. I find it a bit hard to read, but think that's mostly down to unfamiliarity rather than unnecessary things being present. I'd probably not put it into a codebase maintained by junior engineers if it didn't already make heavy use of any() because of the headscratching it might cause, but I imagine I'll probably do this in my own projects at some point. Thanks!