In [1]:
from __future__ import print_function

In [2]:
def foo(n):
    for i in range(n):
        yield i*i

In [3]:
g = foo(4)
g


Out[3]:
<generator object foo at 0xb28ec3c4>

In [4]:
h = foo(5)

The next() builtin function for iterators is available in both Python 2 and 3.


In [5]:
next(g)


Out[5]:
0

The .next() method for iterators is available only in Python 2.


In [6]:
g.next()


---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-6-d7e53364a9a7> in <module>()
----> 1 g.next()

AttributeError: 'generator' object has no attribute 'next'

In [7]:
next(g)


Out[7]:
1

The h and g generators are independent of each other. So iterating through h does not iterfere with g.


In [8]:
for i in h:
    print(i)


0
1
4
9
16

In [9]:
next(g)


Out[9]:
4

In [10]:
next(g)


Out[10]:
9

In [11]:
next(g)


---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
<ipython-input-11-5f315c5de15b> in <module>()
----> 1 next(g)

StopIteration: