1

I want to assign value to 2d array in for loop
This is my code

num = 0
n = 3
arr = [[0] * n] * n

for i in range(n):
    for j in range(n):
        arr[i][j] = num
        num +=1

The output I expected is

[0, 1, 2]
[3, 4, 5]
[6, 7, 8]

But actual output is

[6, 7, 8]
[6, 7, 8]
[6, 7, 8]

Is there any way to fix this?

1

1 Answer 1

3
arr = [[0] * n] * n

It creates n copies of list. So, when you make a change in one list, all others are changed as well. You can change it to something like this:

arr = [[0 for j in n] for i in n]
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.