Strange range

Chris Angelico rosuav at gmail.com
Fri Apr 1 10:31:20 EDT 2016


On Sat, Apr 2, 2016 at 1:16 AM, Fabien <fabien.maussion at gmail.com> wrote:
> On 04/01/2016 03:26 PM, Steven D'Aprano wrote:
>>
>> Incorrect. range is a lazy sequence.
>
>
> But how does range "know" that it has to start from scratch again? As in
> this example:
>
> it = range(10)
> for i in it:
>     if i >= 3:
>         break
> for i in it:
>     # why does it start from zero again?
>     print(i)

It's not an iterator. It's an iterable. So every time you call iter()
on it - which is done implicitly by the starting of the 'for' loop -
you get a completely new iterator which will step through the whole
range object.

*A range object is not an iterator.*

ChrisA



More information about the Python-list mailing list