+ 1
Effect of '*' operation on list and list append in python
code 1 and code 2 produce different outputs (even though same number 2 is being added to the list through + and append() operation ) Code 1:- a=[ [ ] ]*4 a[0]=a[0]+[2] a[0].append(2) print(a). Output1 - [ [2,2], [ ], [ ], [ ] ] _________ Code 2 a=[ [ ] ]*4 a[0].append(2) a[0]=a[0]+[2] print(a) Output 2 - [ [2,2], [2], [2], [2] ] Can anyone throw a light on this difference?
2 Respostas
+ 2
Order matters ;)
+ 1
Order matters that's right, but what surprised me is that in code 2 , a[0].append(2) puts 2 in all lists instead of only the first one