-2

we have an array p = [[none]*5]*6 and we want to fill it with number 1

something like this:

 [[1, none, none, 1, 1],[none, 1, none, 1, none],[none, 1, 1, 1, none], [1, none, 1, none, 1], [none, 1, none, 1, none],[1, none, 1, none, none]]
  • What did you tried so far? Please share the code – Nir Elbaz Dec 31 '20 at 10:56
  • Maybe go back to basics. Read [this](https://stackoverflow.com/questions/2612802/list-changes-unexpectedly-after-assignment-how-do-i-clone-or-copy-it-to-prevent) Try: `p = [[None]*5]*6; p[3][1] = 42; print(p)` and observe what you do wrong. Then [edit] your code to make this better. Lookup [numpy-random-2d-array](https://stackoverflow.com/questions/46984635/numpy-random-2d-array) - research your problem before asking. Read [ask] and take the [tour] to have your questions survive longer and without downvotes. – Patrick Artner Dec 31 '20 at 10:57

1 Answers1

1

Tt isn't a good idea to use p = [[none]*5]*6 because with this expression every list in p is linked together, which causes some weird behaviours like for example:

>>> p = [[None]*5]*6
>>> p
[[None, None, None, None, None], [None, None, None, None, None], [None, None, None, None, None], [None, None, None, None, None], [None, None, None, None, None], [None, None, None, None, None]]
>>> p[0][0] = 1
[[1, None, None, None, None], [1, None, None, None, None], [1, None, None, None, None], [1, None, None, None, None], [1, None, None, None, None], [1, None, None, None, None]]

To create your array you can use a list comprehension: p = [[none]*5 for _ in range(6)] and to randomise it you can create the function:

from random import random
def randomise_array(array):
    for index1, list1 in enumerate(array):
        for index2 in range(len(list1)):
            if random()>0.5:
                array[index1][index2]=1
    return array

PS: None takes a capital "N"

Adrien
  • 36
  • 3