Why isn't range getting exhausted in Python-3? -
if following:
a = range(9) in a: print(i) # must exhausted in a: print(i) # starts over! python's generators, after raising stopiteration, stops looping. how range producing pattern - restarts after every iteration.
as has been stated others, range not generator, sequence type (like list) makes iterable not same iterator.
the differences between iterable, iterator , generator subtle (at least new python).
- an
iteratorprovides__next__method , can exhausted, raisingstopiteration. - an
iterableobject providesiteratoron content. whenever__iter__method called returns new iterator object, can (indirectly) iterate on multiple times. a
generatorfunction returnsiterator, of cause can exhausted.also know is,
forloop automaticly queriesiteratorofiterable. why can writefor x in iterable: passinstead offor x in iterable.__iter__(): passorfor x in iter(iterable): pass.
all of in documentation, imho difficult find. best starting point glossary.
Comments
Post a Comment