Aguy
Aguy

Reputation: 169

__iter__ and __next__ on vector class is doing some weird stuff

I have a vector class that I've been building

# vector.py
class Vector(object):
    def __init__(self, vec:list):
        self._vector = vec
        self._size   = len(vec)

    def __iter__(self):
        self._index = 0
        return self

    def __next__(self):
        if self._index < self._size:
            self._index += 1
            return self._index-1
        else:
            raise StopIteration

Theres a lot more code than this and I have also implemented a __getitem__ dunder function as well. I was playing around in a test file and wanted to do a sum of the vector without using the python sum() function.

from functools import reduce
import vector

vec = vector.Vector([1, 2, 3, -4])
print(reduce(lambda x,y: x+y, vec))

# I would expect 2 to be returned but got 6 instead.
# So I tried something else instead

print(reduce(lambda x,y: x+y, [1, 2, 3, -4]))
# This returns 2 like expected.

So I don't know why it works when I pass reduce() a python list and not the vector class. I guess it's something to do with how I've implemented __iter__ and __next__. What do you guys think?

Upvotes: 0

Views: 73

Answers (1)

TrebledJ
TrebledJ

Reputation: 9007

In your implementation of __next__, you're returning the index instead of the element. [0, 1, 2, 3] was being generated, which sums to 6.

Fix:

    def __iter__(self):
        self._index = 0
        return self

    def __next__(self):
        if self._index < self._size:
            self._index += 1
            return self._vec[self._index-1]
            #      ^^^^^^^^^^             ^
        else:
            raise StopIteration

Upvotes: 1

Related Questions