+ 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.
5 Respuestas
+ 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.
+ 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
+ 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]
+ 1
thanks @ifl
+ 1
@Tejas yes that's correct, the list is created then updated.