0
import random as rand 

weights = np.zeros((3, 4))

print(weights, end = "\n\n")

for i in weights:
  for j in i:
    j = rand.randint(1, 10)

print(weights)

So I was playing around with numpy and decided to make a 2D array filled with 0s. I then wanted to change the values of the elements within the array to random numbers between 1 and 10. Using the above code, the 2D array does not change and remains filled with zeros. Why does python behave this way when it comes to arrays?

To get my desired result, I had to do the following:

import numpy as np
import random as rand 

weights = np.zeros((3, 4))

print(weights, end = "\n\n")

for i in range(len(weights)):
  for j in range(len(weights[i])):
    weights[i][j] = rand.randint(1, 9)

print(weights) 

Is there any better way to do this so that I don't have to resort to using range() and len()?

2
  • np.random.rand(3, 4) Commented Jul 11, 2020 at 6:47
  • Or for random ints - np.random.randint(1, 9, (3, 4)) Commented Jul 11, 2020 at 6:49

1 Answer 1

1

Better way to do it is during init:

# args - low, high, shape
weights = np.random.randint(1, 9, (3, 4))

You can read documentation here.

And as to why python behaves this way, with list comprehension you are not modifying the list, you are creating a new list.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.