+ 4
List problem
arr=[[]]*3 arr[2].append(7) print(arr) OUTPUT : [[7],[7],[7]] why every element gets assigned to the number 7?
4 Respostas
+ 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
+ 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.
+ 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.
+ 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.