0
help me find out the logic behind tahe python lists
l=[] d=[] d.append(0) l.append(d) print(d) print(l) d.append(1) l.append(d) print(d) print(l) the output here is [0] [[0]] [0,1] [[0,1],[0,1]] //""" it has to come this right [[0],[0,1]] """ why the does it happen
1 Odpowiedź
+ 1
Edit :
Ok. Sry Now understood your question. Corrected now..
d is list, a reference type so when appending, the function adds object type it references, not values. So it changing values everytime original references of d list changing.. So it is like
l =[[Refference of list d], [Refference of list d], [...].]
Since you are adding entire list of object type, not primitive type values..
So final list l is number times list d appended..
Naresh Gopanaboina
If you want add only list values, add by
l = l + d
for your expected output, write like as added as lists then use
l = l.append(d.copy())