A generator object supports the iterator protocol. That is, it provides a next()
method (__next__()
in Python 3.x), which is used to step through its execution, and its __iter__
method returns itself. This means that a generator can be used in any language construct which supports generic iterable objects.
# naive partial implementation of the Python 2.x xrange()
def xrange(n):
i = 0
while i < n:
yield i
i += 1
# looping
for i in xrange(10):
print(i) # prints the values 0, 1, ..., 9
# unpacking
a, b, c = xrange(3) # 0, 1, 2
# building a list
l = list(xrange(10)) # [0, 1, ..., 9]