0

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?

Oblomov
  • 8,953
  • 22
  • 60
  • 106
  • Read https://stackoverflow.com/questions/2582138/finding-and-replacing-elements-in-a-list-python for a 2d list you can use a nested list comprehension. – Mazdak Jul 15 '17 at 09:24
  • Possible duplicate of [finding and replacing elements in a list (python)](https://stackoverflow.com/questions/2582138/finding-and-replacing-elements-in-a-list-python) – Oblomov Jul 17 '17 at 09:40

2 Answers2

4

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.

JMAA
  • 1,730
  • 13
  • 24
2

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

Sangwon
  • 21
  • 1