Strange range

Marko Rauhamaa marko at pacujo.net
Fri Apr 1 10:12:49 EDT 2016


Steven D'Aprano <steve at pearwood.info>:

> On Sat, 2 Apr 2016 12:15 am, Marko Rauhamaa wrote:
>> Note to self: range(10) is an iterator factory, not an iterator.
>
> Incorrect. range is a lazy sequence.

Incorrect. You and I agree.

> You can think of range as equivalent to something close to this:
>
> class Range(object):
>     def __init__(self, start, end, step=1):
>         self.start = start
>         self.end = end
>         self.step = step
>
>     def __getitem__(self, index):
>         value = self.start + (index-1)*self.step
>         if value < self.end:
>             return value
>         raise IndexError
>
>     def __iter__(self):
>         try:
>             index = 0
>             while True:
>                 yield self[index]
>                 index += 1
>         except IndexError:
>             return

Yes, I realize it now. I had thought it was:

    def range(start, end=None, step=1):
        if end is None:
            start, end = 0, start
        i = start
        while step * (end - i) > 0:
            yield i
            i += step


Marko



More information about the Python-list mailing list