+ 6
arr=[[]]*3 arr[0].append(7) print(arr)
why does 7 is appended in all the index instead of first list https://code.sololearn.com/cS95sGnvXmLj/?ref=app
9 Answers
+ 8
Good question.
I assume the inner arrays are just copied in the sense, that they point to the same address.
That's why if you modify one, you will modify all.
For arr=[[],[],[]] it works as intended
+ 2
actually,
arr=[[]]*3 multiplies the inner list into three
It will make like this,
[ [ ], [ ],[ ] ]
so if you index it by arr[0],
it refers to the outer big list which contains three list
means, [ ]
so it will append in all
if you wanna append in first inner list,
you have to append like below,
arr[0][0].append(7)
if you are still struggling, just mention my name in the comment
I will help you more!!
+ 2
Matthias Yeah, I think what you said was right, because "arr[0] is arr[1] is arr[2]" returns True, meaning they all point to the same address(?)
+ 2
It's because when you multiply a list, you multiply the reference of that list, meaning the three lists are actually the same list. So, when you index the first element and append 7 to it, it appends 7 to the list, which also changes the other two, because they're actually the same list. That's why you should use list comprehensions when you want to easily make multidimensional lists.
So you were right!
+ 1
Hemath Kumar and Matthias thank you for the reply. So if I get it right then arr=[]*3 has only one element in the list and arr=[[],[],[]] has three elements, although they look same in the end.
+ 1
Hemath Kumar
But
arr=[[]]*3
arr[0][0].append(7)
print(arr)
does not compile.
What you mean would be one step deeper. Like
arr = [ [ [1], [2] ] , [3] ]
Where print(arr[0][0]) would output [1]
but for
arr = [ [1,2] , [3] ]
it would be 1, i.e. no list, i.e. not able to append something
arr[0].append(7) is actually right, but does not work as intended when the array is build with *3 instead of manually build three arrays.
+ 1
Akash Gupta to get around this, you can try "arr = [[] for i in range(3)]".
+ 1
ok guys . Thanks a lot
0
yeah! I'm wrong !! Sorry for this shit