1

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.]].

darthbith
  • 18,484
  • 9
  • 60
  • 76

3 Answers3

4

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)
Thomas Jungblut
  • 20,854
  • 6
  • 68
  • 91
  • I know it may sound arrogant, however, in this solution, in my opinion, we miss the main problem that OP encounters. Working with mutable and immutable in Python. Don't you think? – storaged Sep 15 '18 at 10:12
2

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.

storaged
  • 1,837
  • 20
  • 34
0

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]])]
kerastf
  • 499
  • 3
  • 11