Reputation: 9625
I have a 2D array in python, like the following:
2d_array_1 =[[0,1],[1,0]]
And want to create a second array of the same size, with all values initialized to zero.
How can I do that in python, if the size of the initial array can vary?
Upvotes: 0
Views: 6453
Reputation: 51
I think above answer should be fixed.
first_array = [[0,1],[1,0]]
second_array = [ [0] * len(first_array[0]) ] * len( first_array )
second_array[0][0] = 1
print(second_array) # [[1, 0], [1, 0]]
To prevent this, you can use below code
second_array = [ [0 for _ in range(len(first_array[0]))] for _ in range(len( first_array )) ]
second_array[0][0] = 1
print(second_array) # [[1, 0], [0, 0]]
Upvotes: 5
Reputation: 2049
You can get the size of a list by len(list)
and you can initialise a list of length n
with a given value val
like this: list = [val] * n
. Putting these two together you get:
first_array = [[0,1],[1,0]]
second_array = [ [0] * len(first_array[0]) ] * len( first_array )
assuming of course that first_array
is of the form you're expecting.
Upvotes: 4