linq - Inconsistent behavior of python generators -


the following python code produces [(0, 0), (0, 7)...(0, 693)] instead of expected list of tuples combining of multiples of 3 , multiples of 7:

multiples_of_3 = (i*3 in range(100)) multiples_of_7 = (i*7 in range(100)) list((i,j) in multiples_of_3 j in multiples_of_7) 

this code fixes problem:

list((i,j) in (i*3 in range(100)) j in (i*7 in range(100))) 

questions:

  1. the generator object seems play role of iterator instead of providing iterator object each time generated list enumerated. later strategy seems adopted .net linq query objects. there elegant way around this?
  2. how come second piece of code works? shall understand generator's iterator not reset after looping through multiples of 7?
  3. don't think behavior counter intuitive if not inconsistent?

as discovered, object created generator expression iterator (more precisely generator-iterator), designed consumed once. if need resettable generator, create real generator , use in loops:

def multiples_of_3():               # generator     in range(100):        yield * 3 def multiples_of_7():               # generator     in range(100):        yield * 7 list((i,j) in multiples_of_3() j in multiples_of_7()) 

your second code works because expression list of inner loop ((i*7 ...)) evaluated on each pass of outer loop. results in creating new generator-iterator each time around, gives behavior want, @ expense of code clarity.

to understand going on, remember there no "resetting" of iterator when for loop iterates on it. (this feature; such reset break iterating on large iterator in pieces, , impossible generators.) example:

multiples_of_2 = iter(xrange(0, 100, 2))  # iterator in multiples_of_2:     print # prints nothing because iterator spent in multiples_of_2:     print 

...as opposed this:

multiples_of_2 = xrange(0, 100, 2)        # iterable sequence, converted iterator in multiples_of_2:     print # prints again because new iterator gets created in multiples_of_2:     print 

a generator expression equivalent invoked generator , can therefore iterated on once.


Comments

Popular posts from this blog

Unable to remove the www from url on https using .htaccess -