Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python execute code only if for loop did not begin iteration (with generator)?

The else block in a for/else clause gets executed if the iteration finishes but is not interrupted by break, so I read.

Is there a language construct which would let me write something which executes only if the for loop did not begin iteration? If I was using a tuple or list, I would do something like this:

if seq:
    for x in seq:
         # something
else:
    # something else

But when I use a generator, I don't get the behavior 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 creating a tuple or a list from the generator, while also using a for loop? I could use next() in a while loop and try to catch StopIteration, but I'd like to see if there's a nice way to do it with for.

like image 866
2rs2ts Avatar asked Aug 07 '13 19:08

2rs2ts


People also ask

Does for-loop start 0 Python?

For Loops using range() start states the integer value at which the sequence begins, if this is not included then start begins at 0.

Does a while loop execute at least once Python?

There are two variations of the while loop – while and do-While. The difference between the two is that do-while runs at least once. A while loop might not even execute once if the condition is not met.

Will a for-loop always execute at least once?

With a do while loop the condition is not evaluated until the end of the loop. Because of that a do while loop will always execute at least once. A for-loop always makes sure the condition is true before running the program. Was this answer helpful?


1 Answers

n = -1
for n, i in enumerate(it):
    do_stuff()
if n < 0:
    print 'Done'
like image 170
glglgl Avatar answered Sep 18 '22 02:09

glglgl