pythonpython-3.xrange

Why isn't range getting exhausted in Python 3?


If I do the following:

a = range(9)

for i in a:
    print(i)

# Must be exhausted by now
for i in a:
    print(i)

# It starts over!

Python's generators, after raising StopIteration, normally stop looping. How then is range producing this pattern - it restarts after every iteration.


Solution

  • As has been stated by others, range is not a generator, but sequence type (like list) that makes it an iterable which is NOT the same as an iterator.

    The differences between iterable, iterator and generator are subtle (at least for someone new to python).

    All of that IS in the documentation, but IMHO somewhat difficult to find. The best starting point is probably the Glossary.