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 iterator provides __next__ method , can exhausted, raising stopiteration.
  • an iterable object provides iterator on content. whenever __iter__ method called returns new iterator object, can (indirectly) iterate on multiple times.
  • a generator function returns iterator, of cause can exhausted.

  • also know is, for loop automaticly queries iterator of iterable. why can write for x in iterable: pass instead of for x in iterable.__iter__(): pass or for x in iter(iterable): pass.

all of in documentation, imho difficult find. best starting point glossary.


Comments

Popular posts from this blog

java - Plugin org.apache.maven.plugins:maven-install-plugin:2.4 or one of its dependencies could not be resolved -

Round ImageView Android -

How can I utilize Yahoo Weather API in android -