python setting value to list elements -


basically i'm trying is, create nestled list , set value of 1 of element function of other elements in list.

>>> = [[1]*5]*5 >>> [[1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1]] >>> a[2][2] = a[0][2] + a[2][1] >>> [[1, 1, 2, 1, 1], [1, 1, 2, 1, 1], [1, 1, 2, 1, 1], [1, 1, 2, 1, 1], [1, 1, 2, 1, 1]] >>> a[3][2]    2 >>> a[4][2] 2 >>> a[4][4] 1 

i set value of a[2][2] same value got set every element in 3rd column. going on , how can desired behavior?

what happens a ends containing 5 references same sublist. when change 1 sublist, change.

to see this, apply id() each of sublists:

>>> map(id, a) [8189352, 8189352, 8189352, 8189352, 8189352] 

as can see, have same id, meaning same object.

to fix, replace

a = [[1]*5]*5 

with

a = [[1]*5 _ in range(5)] 

now sublists independent objects:

>>> map(id, a) [21086256, 18525680, 18524720, 19331112, 18431472] 

Comments