Reputation:
I'm trying to add different arrays in Python to an empty list x by using x.append(). This is what I did:
x = []
y = np.zeros(2)
for i in range(3):
y += 1
x.append(y)
x
[array([3., 3.]), array([3., 3.]), array([3., 3.])]
The problem as you see is that it repeats the last result, and what I want is to get a list with different arrays within, such as: [[3., 3.],[4., 4.], [5., 5.]]
.
Upvotes: 1
Views: 128
Reputation: 1847
Commenting on your problem in detail.
Python works with the same instance of y
all the time.
At the end of your loop, you can think of your list x
as: x = [y, y, y]
and each change made on y
was applied to each entry in the x
.
If you want to have a unique copy at each iteration you need to make a full copy of the variable.
import copy
x = []
y = np.zeros(2)
for i in range(3):
y = copy.deepcopy(y) # based on the comment it is enough
y += 1 # to put y = y + 1 (also creates a new copy)
x.append(y)
I hope it helps you understand it a bit more what Python did (see also Immutable vs Mutable types for more details).
However, it seems to be quite inefficient.
Upvotes: 1
Reputation: 509
Use the full() function of numpy.You have to specify the dimension of array(in ur case 1 row ,2 clolumns) and the value u want it to fill with,ie value provided by i
x = []
y = np.zeros(2)
for i in range(3):
y =np.full((1,2),i)
x.append(y)
x
[array([[0, 0]]), array([[1, 1]]), array([[2, 2]])]
Upvotes: 0
Reputation: 20969
You're changing the same array over the whole loop, move the creation of y
into your loop:
x=[]
for i in range(3):
y = np.zeros(2) + i
x.append(y)
Upvotes: 4