Why is the range not 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 generators after raising StopIteration usually stop the loop. How then does the range produce this pattern - it restarts after each iteration.

+5
source share
3 answers

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 .

+6
source

range is a kind of immutable sequence type. The iteration does not exhaust it.

 >>> a = iter(range(9)) # explicitly convert to iterator >>> >>> for i in a: ... print(i) ... 0 1 2 3 4 5 6 7 8 >>> for i in a: ... print(i) ... >>> 
+3
source

range not a generator; it is a type of sequence , such as strings or lists .

So

 for i in range(4): 

no different from

 for i in "abcd": 
+1
source

Source: https://habr.com/ru/post/1209210/


All Articles