2

Basically, I'm in following situation - I generate a list, e.g.

l = [2*x for x in range(10)]

which I iterate through later on multipletimes, e.g.

for i in l: print i    # 0,2,4,6,8,10,12,14,16,18
for i in l: print i    # 0,2,4,6,8,10,12,14,16,18
for i in l: print i    # 0,2,4,6,8,10,12,14,16,18

The problem is that the list is way too large to fit into memory, hence I use its generator form, i.e.:

l = (2*x for x in range(10))

However, after this construction only first iteration works:

for i in l: print i    # 0,2,4,6,8,10,12,14,16,18
for i in l: print i    #
for i in l: print i    #

Where is the problem? How may I iterate through it multipletimes?

2 Answers 2

6

Your generator is exhausted the first time. You should recreate your generator each time to renew it:

l = (2*x for x in range(10))
for i in l: print i
l = (2*x for x in range(10))
for i in l: print i

(Note: you should use xrange in python 2 because range creates a list in memory)

You can create also a shortcut function to help you or even a generator function:

def gen():
    for i in range(10):
        yield 2 * i

and then:

 for i in gen(): print i
 for i in gen(): print i
Sign up to request clarification or add additional context in comments.

3 Comments

Should probably note that xrange is the generator version of range in python 2, whereas range in python 3+ is a generator and there is no xrange.
@MylesGallagher yes I updated. I guessed we were talking only for python 2.
I like the generator function. Alternatively, for such a simple generator, a lambda would be acceptable, eg gen = lambda : (2*x for x in xrange(10)). And of course either of these functions could be given multiplier and length args to make them more versatile.
0

You can also iterate on the generator directly:

for i in (2*x for x in range(10)): print i
for i in (2*x for x in range(10)): print i
...

1 Comment

True, but that's not DRY.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.