-1

I am trying to create a empty array in Python. Later I want to write to every space a unique number.
Here is my code:

import numpy as np

# First Method
weights = [[0]*3]*3
for i in range(len(weights)):
    for j in range(len(weights[0])):
        weights[i][j] = float(np.random.rand(1))
print (weights)

# Second Method
weights2 = [[0,0,0],[0,0,0],[0,0,0]]
for i in range(len(weights2)):
    for j in range(len(weights2[0])):
        weights2[i][j] = float(np.random.rand(1))
print (weights2)

And here is the output:

first: [[0.08888843613599318, 0.6057538355394358, 0.9116018147777744], [0.08888843613599318, 0.6057538355394358, 0.9116018147777744], [0.08888843613599318, 0.6057538355394358, 0.9116018147777744]]
second: [[0.6196830850283566, 0.4767956303875597, 0.11175364311603775], [0.6237674876857202, 0.5810440548445903, 0.10874630848820122], [0.6923495438022649, 0.38815857621698835, 0.22380090955172283]]

As you can see the first array has three sets of the same three numbers while the second one doesn't.
My question therefore is why and how can I change it?

hidefromkgb
  • 5,834
  • 1
  • 13
  • 44
98coolmen
  • 5
  • 2

1 Answers1

-1

My question therefore is why and how can I change it?

Replace weights = [[0]*3]*3 using list comprehension as follows:

weights = [[0]*3 for _ in range(3)]
Daweo
  • 31,313
  • 3
  • 12
  • 25