As others have said, range not a generator, but has a sequence type (like a list) that makes it iterable , which does NOT match the iterator .
The differences between iterable , iterator and generator are subtle (at least for someone new to python).
- An
iterator provides the __next__ method and can be exhausted, thereby raising StopIteration . - An
iterable is an object that provides an iterator according to its contents. Whenever its __iter__ method __iter__ called, it returns a NEW iterator object, so you can (indirectly) iterate over it several times. A generator is a function that returns an iterator that can be exhausted.
It is also useful to know that the for loop automatically queries the iterator any iterable . That is why you can write for x in iterable: pass instead of for x in iterable.__iter__(): pass or for x in iter(iterable): pass .
All this is in the documentation, but IMHO is somewhat difficult to find. The best starting point is probably Glossary .
source share