I’m trying to represent an array of evenly spaced floats, an arithmetic progression, starting at a0 and with elements a0, a0 + a1, a0 + 2a1, a0 + 3a1, …
This is what numpy’s arange() method does, but it seems to allocate memory for the whole array object and I’d like to do it using an iterator class which just stores a0, a1 and n (the total number of elements, which might be large).
Does anything that does this already exist in the standard Python packages?
I couldn’t find it so, ploughed ahead with:
class mylist():
def __init__(self, n, a0, a1):
self._n = n
self._a0 = a0
self._a1 = a1
def __getitem__(self, i):
if i < 0 or i >= self._n:
raise IndexError
return self._a0 + i * self._a1
def __iter__(self):
self._i = 0
return self
def next(self):
if self._i >= self._n:
raise StopIteration
value = self.__getitem__(self._i)
self._i += 1
return value
Is this a sensible approach or am I revinventing the wheel?
Well, one thing that you are doing wrong is that it should be
for i, x in enumerate(a): print i, x.Also, I’d probably use a generator method instead of the hassle with the
__iter__andnext()methods, especially because your solution wouldn’t allow you to iterate over the samemylisttwice at the same time with two different iterators (asself._iis local to the class).This is probably a better solution which gives you random access as well as an efficient iterator. The support for the
inandlenoperators are thrown in as a bonus 🙂