Always prefer xrange above range?

2

range creates a list in memory with the number of elements defined by the programmer. Since xrange has more performance, I do not know if in all cases, since it does not end up generating a list.

Should I always use xrange above range ? Are there instances where the use of range is more advantageous than the use of xrange ?

    
asked by anonymous 17.03.2017 / 03:42

1 answer

6

In fact, in Python 3 there is no longer the equivalent of the range of Python 2 - the range is now what was the old xrange.

But in the code in Python 2, yes, there is no reason to use the normal range. The range (from Python 3 - xrange) "seems" a function, but it is a class, quite simple to do the same. And the efficiency is so much bigger than a list, that the question that remains is "my God, how did you ever make the range of Python 2 ??": -)

In very little case in which you will call a function that really needs a list, you can convert a range object to a list by doing list(xrange(10)) .

How to create your: everything an object needs is a way to (1) retrieve a given number from an index, (2) need to interact numbers starting at "beginning", and going to the "end" of "step by step", if used in for , for example. (3) Also needs to return its own length.

In Python, this means you have to have a class that implements (1) __getitem__ , (2) __iter__ , (3) __len__ :

class MyRange(object):  # em Python 2 é obrigatório herdar de object
    def __init__(self, start, stop=None, step=1):
        if stop is None:
            stop = start
            start = 0
        self.start = start
        self.stop = stop
        self.step = step

    def __getitem__(self, index):
        return self.start + self.step * index

    def __len__(self):
        return (self.stop - self.start) // self.step

    def __iter__(self):
        v = self.start
        while (v < self.stop) if self.step > 0 else (v > self.stop):
            yield v
            v += self.step

This class is functionally the same. It does not handle some corner cases, but it also does not check if any of the values is an integer: that is, it works for decimal numbers as well.

    
17.03.2017 / 04:47