from __future__ import print_function
def foo(n):
for i in range(n):
yield i*i
g = foo(4)
g
<generator object foo at 0xb28ec3c4>
h = foo(5)
The next() builtin function for iterators is available in both Python 2 and 3.
next(g)
0
The .next() method for iterators is available only in Python 2.
g.next()
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-6-d7e53364a9a7> in <module>() ----> 1 g.next() AttributeError: 'generator' object has no attribute 'next'
next(g)
1
The h and g generators are independent of each other. So iterating through h does not iterfere with g.
for i in h:
print(i)
0 1 4 9 16
next(g)
4
next(g)
9
next(g)
--------------------------------------------------------------------------- StopIteration Traceback (most recent call last) <ipython-input-11-5f315c5de15b> in <module>() ----> 1 next(g) StopIteration: