Jun-08-2017, 02:48 PM
In Python 3 range() is an iterator.
That means that it will not generate all values at once and produce a lust for example but it returns one value per call.
What I mean:
Here is the equivalent of a for loop as it is in above code:
That means that it will not generate all values at once and produce a lust for example but it returns one value per call.
What I mean:
>>> r = range(5) >>> i = iter(r) >>> r range(0, 5) >>> i <range_iterator object at 0x7f52ed2cdcc0> >>> next(i) 0 >>> next(i) 1 >>> next(i) 2 >>> next(i) 3 >>> next(i) 4 >>> next(i) Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration >>>Looping over a range(5) is not looping over a list ( what it was in Python 2 range() ) but instead next() is called and 0 is produced the first time. Than next() is called again and is produced 1. It keeps the state so all is in order. Until all vallues are out and StopIteration is raised.
Here is the equivalent of a for loop as it is in above code:
>>> r = range(5) >>> i = iter(r) >>> while True: ... try: ... next(i) ... except StopIteration: ... break ... 0 1 2 3 4 >>>