I need some explanation for the following results(in python 2.7) | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

I need some explanation for the following results(in python 2.7)

>>>a=[[0]*2]*2 >>>a[0][0]=5 >>>a [[5,0],[5,0]] why does in outer list has repeated elements but not in inner list ? i expected the result to be [[5,5],[5,5]] as i used repetition for inner as well as outer loop.

18th Jan 2017, 4:15 AM
nitesh
5 Answers
+ 2
see code : https://code.sololearn.com/cbss5IFkuyAh/?ref=app Lists are mutable, and elements of the outer list are in fact pointers to the (same) inner list location in memory.
18th Jan 2017, 5:27 AM
ifl
ifl - avatar
+ 2
someone correct me if i am rwong but doesn't >>>a=[[0]*2]*2 get executed first then >>>a[0][0]=5,so the list gets created then updated
19th Jan 2017, 7:03 AM
Tejas Devgekar
Tejas Devgekar - avatar
+ 1
this is because the repetition operator on a list of one element creates a list of independent items y=[1]*3 y[0]=5 print(y) >>>> [5,1,1]
18th Jan 2017, 5:11 AM
ifl
ifl - avatar
+ 1
thanks @ifl
18th Jan 2017, 11:42 AM
nitesh
+ 1
@Tejas yes that's correct, the list is created then updated.
19th Jan 2017, 7:04 AM
ifl
ifl - avatar