+ 4

List problem

arr=[[]]*3 arr[2].append(7) print(arr) OUTPUT : [[7],[7],[7]] why every element gets assigned to the number 7?

26th Jan 2018, 3:23 PM
Tilok Saha
Tilok Saha - avatar
4 Answers
+ 3
alright then explain me this arr=[[],[],[]] arr[2]. append (7) print(arr) OUTPUT : [[],[],[7]] why every slot isn't filled with the number 7
26th Jan 2018, 3:51 PM
Tilok Saha
Tilok Saha - avatar
+ 2
now I got it arr=[[]]*3 print(id(arr[0])) print(id(arr[1])) print(id(arr[2])) b=[[],[],[]] print(id(b[0])) print(id(b[1])) print(id(b[2])) first three gave me same result,whereas the other 3 gave me different result....which means if I assign any one of the element in arr the other two slot will automatically get filled by the value I put...where as in b it has 3 different memory location which means if I assign any one of the slot the other two will remain unaffected.
26th Jan 2018, 4:17 PM
Tilok Saha
Tilok Saha - avatar
+ 1
Well you're appending the number seven to an array of an array, so python takes it as "place this number into every free slot of the array" Edit: Nevermind, this isn't explained very well. See my other comment.
26th Jan 2018, 3:40 PM
SplittyDev
SplittyDev - avatar
+ 1
The reason for that is, that [[]]*3 is not the same as [[], [], []]. The first one with the multiplication creates three references to the same list, whereas the second one creates three different lists. You are basically assigning 7 to one list, but the other two lists are referenced to the third one.
26th Jan 2018, 3:56 PM
SplittyDev
SplittyDev - avatar