In fact, in Python 3 there is no longer the equivalent of the "range" of Python 2 - the "range" is now what used to be the old xrange.
But in Python 2 code, yes, there is no reason to use the normal "range". The "range" (from Python 3 - xrange) "seems" a function, but it is a class, until quite simple to do the same. And the efficiency is so much greater than a list, the question that remains is "My God, how did you one day make the range of Python 2?? " :-)
In the very little used 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: all an object of this needs is a way to (1) retrieve a number given an index, (2) need to interact the numbers starting at "start", and going to the "end" of "step by step" if used in a for
, for example. (3) You also need to return your 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 treat some corner cases, but it also does not check whether any of the values is an integer: that is, it works for decimal numbers as well.
In short, in Python 3, use
range
, in Python 2,xrange
.– Woss
@Andersoncarloswoss xrange does not even exist in python3, you have no alternative :P range 4ever
– Miguel