Like a loop through a generator

How can I skip a generator? I thought about this:

gen = function_that_returns_a_generator(param1, param2) if gen: # in case the generator is null while True: try: print gen.next() except StopIteration: break 

Is there a more pythonic way?

+46
python generator
Jul 18 '12 at 10:21
source share
6 answers

Simply

 for x in gen: # whatever 

will do the trick. Note that if gen always returns True .

+89
Jul 18 '12 at 10:24
source share
 for item in function_that_returns_a_generator(param1, param2): print item 

You do not need to worry about the test to find out if there is anything returned by your function, as if nothing returned, you will not enter the loop.

+15
Jul 18 '12 at 10:23
source share

Just treat it like any other iterable:

 for val in function_that_returns_a_generator(p1, p2): print val 

Note that if gen: will always be True, so this is a false test

+4
Jul 18 '12 at 10:24
source share

If you do not need the output of the generator because you only care about its side effects, you can use the following single-line:

 for _ in gen: pass 
+3
Nov 24 '15 at 10:25
source share

You can simply skip it:

 >>> gen = (i for i in range(1, 4)) >>> for i in gen: print i 1 2 3 

But keep in mind that you can loop only once. The following time generator will be empty:

 >>> for i in gen: print i >>> 
+3
Feb 01 '16 at 21:27
source share

If you want to manually move the generator (i.e., work with each cycle manually), you can do something like this:

  from pdb import set_trace() for x in gen: set_trace() #do whatever you want with x at the command prompt #use pdb commands to step through each loop of the generator eg, >>c #continue 
-one
Jan 16 '14 at 6:53
source share



All Articles