+ 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?

19th Nov 2020, 11:22 AM
Tushar Kumar
Tushar Kumar - avatar
2 odpowiedzi
+ 2
Order matters ;)
21st Nov 2020, 12:05 PM
::sк::
::sк:: - avatar
+ 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
21st Nov 2020, 12:20 PM
Tushar Kumar
Tushar Kumar - avatar