Suppose that I am looping over a iterable and would like to take some action if the iterator is empty. The two best ways that I can think of to do this are
for i in iterable:
# do_something
if not iterable:
# do_something_else
and
empty = True
for i in iterable:
empty = False
# do_something
if empty:
# do_something_else
The first depends on the the iterable being a collection (so useless for when the iterable gets passed into the function/method where the loop is) and the second sets empty
on every pass through the loop which seems ugly.
Is there another way that I'm missing or is the second alternative the best? It would be really cool if there was some clause that I could add to the loop statement that would handle this for me much like else
makes not_found
flags go away.
[Deleted specific example because it seems to be confusing people]
I am not looking for clever hacks.
I am not looking for solutions that involve a lot of code
I am looking for a simple language feature. I am looking for a clear and pythonic way to iterate over an iterable and take some action if the iterable is empty that any experienced python programmer will be understand. If I could do it without setting a flag on every iteration, that would be fantastic. If there is no simple idiom that does this, then forget about it.