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


the else block in for/else clause gets executed if iteration finishes not interrupted break, so read.

is there language construct let me write executes if for loop did not begin iteration? if using tuple or list, this:

if seq:     x in seq:          # else:     # else 

but when use generator, don't behavior want:

>>> g = (x x in range(2)) >>> x in g: ...     print x ... else: ...     print "done" ...  0 1 done    # don't want "done" here >>> g = (x x in range(2) if x > 1) >>> if g: ...     x in g: ...         print x ... else: ...     print "done" ...  >>>     # expecting "done" here 

how can without exhausting creating tuple or list generator, while using for loop? use next() in while loop , try catch stopiteration, i'd see if there's nice way for.

i can't think of better way updating boolean inside loop.

any_results = false x in g:     any_results = true     print x if not any_results:     print 'done' 

Comments

Popular posts from this blog

plot - Remove Objects from Legend When You Have Also Used Fit, Matlab -

java - Why does my date parsing return a weird date? -

Need help in packaging app using TideSDK on Windows -