Different outputs for the same thing in python -
sr = [12,13,4] thre = 1 kaju = [] p in range(len(sr)): sr[p] -= thre kaju.append(sr) print sr print kaju
result came out as:
[11, 13, 4] [11, 12, 4] [11, 12, 3] [[11, 12, 3], [11, 12, 3], [11, 12, 3]
i don't know why sr , kaju not same
lists passed reference in python. when appending sr
kaju
, appending reference same list. print statements reflect changes sr
upon each iteration, kaju
contains bunch of references same list.
if want elements of kaju
reflect changes on each iteration, must copy sr
's value on each iteration, can done built-in list()
function
for p in range(len(sr)): sr[p] -= thre kaju.append(list(sr)) print sr print kaju
outputs:
[11, 13, 4] [11, 12, 4] [11, 12, 3] [[11, 13, 4], [11, 12, 4], [11, 12, 3]]
Comments
Post a Comment