snippets/Python-range-function-impro...

1.7 KiB

range function improved for Python2

This class allows you to have a similar performance to the python3 range in python2

This class doesn't load all the elements of the range at the same time in a list in memory.

class range:
    def __init__(self, start, end=None, step=None):
        if step is not None and step > 0 and  end is not None and end <= start:
            raise ValueError("The start value is lower than the end")
        elif end is not None and end < start and step is not None and step > 0:
            raise ValueError("The end value can't be higher than the start if the step is higher than 0")
        elif step == 0:
            raise ValueError("Step value can't be 0")
        if end is None:
            end = start
            start = 0
        if step is None:
            step = 1
        self.start = start - step
        self.end = end
        self.step = step
        self.__actual = 0

    def __getitem__(self, index):
        if index < 0:
            raise IndexError("Index value can't be lower than 0")
        output = self.step * (index + 1) + self.start
        if self.end > self.start and output >= self.end:
            raise IndexError("Index out of range")
        elif self.end < self.start and output <= self.end:
            raise IndexError("Index out of range")
        return output
 
    def __next__(self):
        val = None
        try:
            val = self.__getitem__(self.__actual)
        except IndexError:
            raise StopIteration()
        self.__actual += 1
        return val

>>> from_0_to_9 = range(10)
>>> print(list(from_0_to_9))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> from_1_to_minus9 = range(1, -10, -1)
>>> for n in from_1_to_minus9:
>>>     print(n)
1
0
-1
...
-8
-9