1

I recently came across the idea of generators in Python, so I made a basic example for myself:

def gen(lim):
    print 'This is a generator'
    for elem in xrange(lim):
        yield elem
    yield 'still generator...'
    print 'done'

x = gen
print x
x = x(10)
print x
print x.next()
print x.next()

I was wondering if there was any way to iterate through my variable x and have to write out print x.next() 11 times to print everything.

3 Answers 3

2

That's the whole point of using a generator in the first place:

for i in x:
    print i
This is a generator
0
1
2
3
4
5
6
7
8
9
still generator...
done
Sign up to request clarification or add additional context in comments.

2 Comments

If I wanted to use the .next() method, I would just treat x like a list and use .next() to iterate through the list?
@MaxKim Why would you want to use the .next() method? You can iterate through a generator using a simple for-loop as shown above.
2

Yes. You can actually just iterate through the generator as if it were a list (or other iterable):

x = gen(11)
for i in x:
    print i

Calling x.next() is actually not particular to generators — you could do it with a list too if you wanted to. But you don't do it with a list, you use a for loop: same with generators.

Comments

1

You can use for loop to iterate generator.

def gen(lim):
    print 'This is a generator'
    for elem in xrange(lim):
        yield elem
    yield 'still generator...'
    print 'done'

for x in gen(10):
    print x

Comments

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.