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?

2

2 Answers 2

5

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

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

Comments

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.

1 Comment

you are simply duplicating the array len(first_array) times. This would lead to side effects. Sangwon has a better answer below that prevents that.

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.