Reputation: 13
While testing code some errors appeared - after a mathematical operation, a list 'shrinks' down to itself's last item
In the Python 3.3 interpreter it works fine...
a = [a + b for a, b in zip(a, b)]
I'm using this code to add some list items
a = [1, 2, 3]
b = [2, 3, 2]
this works fine and returns
>>> a
[3, 5, 5]
>>> b
[2, 3, 2]
Then I wrote a class to handle more lists:
class Vector:
def __init__(self, name = '', vector = []):
self.__name = name
self.__vector = vector
def add_row_to_scalar_multiple(self, vector):
self.__vector = [self.__vector + vector.__vector for self.__vector, vector.__vector in zip(self.__vector, vector.__vector)]
def __str__(self):
vec = ('{0} = {1}'.format(self.__name, self.__vector))
formatted_vec = vec.replace(',', '')
return formatted_vec
When running the code with the same lists as above, one list is reduced to a single integer
vec_a = Vector('a', [1, 2, 3])
vec_b = Vector('b', [2, 3, 2])
a = [1, 2, 3]
b = [2, 3, 2]
vec_b.add_row_to_scalar_multiple(vec_a)
a = 3
b = [3, 5, 5]
I just can't figure out what I'm doing wrong, so anyone could please help??
Upvotes: 1
Views: 127
Reputation: 49826
self.__vector = [self.__vector + vector.__vector for self.__vector, vector.__vector in zip(self.__vector, vector.__vector)]
See that? You're assigning values to self.__vector, vector.__vector
in the loop for self.__vector, vector.__vector in zip(self.__vector, vector.__vector)
.
Upvotes: 6
Reputation: 39000
a = [a + b for a, b in zip(a, b)]
You should not be using "a, b" for the iteration variables, they are not the same things as the original lists, and this led you to make the mistake of thinking they should always be the same as the things you're zipping.
It should be for example a = [aa + bb for aa, bb in zip(a, b)]
And then in converting it to your class, you would have seen, instead of this:
self.__vector = [self.__vector + vector.__vector for self.__vector, vector.__vector in zip(self.__vector, vector.__vector)]
You should have this:
self.__vector = [aa + bb for aa, bb in zip(self.__vector, vector.__vector)]
Also, your function should probably be called __iadd__
, but that's beside the point.
On an unrelated note:
self.__vector = vector
This line has two problems. For one thing, it's just storing a reference to the list that is passed in (which may not be what you want). The much bigger issue is that your default vector = []
argument is the same list every time. Mutable types for defaults should be avoided unless you know what you're doing. I would suggest self.__vector = list(vector)
.
Upvotes: 3