Join the Stack Overflow Community
Stack Overflow is a community of 6.2 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

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.

share|improve this question
up vote 2 down vote accepted

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
share|improve this answer
    
If I wanted to use the .next() method, I would just treat x like a list and use .next() to iterate through the list? – Max Kim Jul 14 '13 at 15:20
    
@MaxKim Why would you want to use the .next() method? You can iterate through a generator using a simple for-loop as shown above. – arshajii Jul 14 '13 at 15:26

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.

share|improve this answer

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
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.