The else block in the for / else clause is triggered if the iteration ends but break is not interrupted, so I read .
Is there a language construct that would allow me to write something that only runs if the for loop did not start with an iteration? If I used tuple or list , I would do something like this:
if seq: for x in seq: # something else: # something else
But when I use the generator, I do not get the behavior that I want:
>>> g = (x for x in range(2)) >>> for x in g: ... print x ... else: ... print "done" ... 0 1 done # I don't want "done" here >>> g = (x for x in range(2) if x > 1) >>> if g: ... for x in g: ... print x ... else: ... print "done" ... >>> # I was expecting "done" here
How can I do this without exhausting the creation of a tuple or list from the generator, as well as using the for loop? I could use next() in a while and try to catch StopIteration , but I would like to see if there is a good way to do this with for .
source share