Why isn't range getting exhausted in Python-3?
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).
- An
iterator
provides a__next__
method and can be exhausted, thus raisingStopIteration
. - An
iterable
is a object that provides aniterator
over its content. Whenever its__iter__
method is called it returns a NEW iterator object, thus you can (indirectly) iterate over it multiple times. A
generator
is a function that returns aniterator
, which of cause can be exhausted.Also good to know is, that the
for
loop automaticly queries theiterator
of anyiterable
. Which is why you can writefor x in iterable: pass
instead offor x in iterable.__iter__(): pass
orfor x in iter(iterable): pass
.
All of that IS in the documentation, but IMHO somewhat difficult to find. The best starting point is probably the Glossary.
range
is a kind of immutable sequence type. Iterating it does not exhaust it.
>>> a = iter(range(9)) # explicitly convert to iterator>>>>>> for i in a:... print(i)...012345678>>> for i in a:... print(i)...>>>
range
is not a generator, it's a sequence type, like strings or lists.
So
for i in range(4):
is no different than
for i in "abcd":