2 years ago

#34444

test-img

LukasFun

Sub-arrays can't be changed individually when created at the same time

I created an array with two sub-arrays containing zeros:

a=[[0]*3]*2

This looks like so:

[[0, 0, 0], [0, 0, 0]]

I try to modify the first value of the first sub-array like this:

a[0][0] = 1

Then the array looks like this:

[[1, 0, 0], [1, 0, 0]]

The second sub-array was changed as well. If i create the sub-arrays individually by writing

a=[0]*2
a[0]=[0]*3
a[1]=[0]*3

and then execute the same command to modify the first value, the result looks like this:

[[1, 0, 0], [0, 0, 0]]

Why does the array behave differently in these cases and is there a way to change values of sub-arrays when initializing them together?

python

arrays

sub-array

0 Answers

Your Answer

Accepted video resources