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

Popular posts from this blog

wordpress - (T_ENDFOREACH) php error -

Export Excel workseet into txt file using vba - (text and numbers with formulas) -

Using django-mptt to get only the categories that have items -