New course! Every coder should learn Generative AI!
Try a free lesson+ 2
Append list affecting all entries
Hi Everyone, Do you know why the append method for nested list affects also all the others ? Instead, if I overwrite one sublist only that particular entry changes. Thanks in advance. https://code.sololearn.com/cOG4R0VgogqZ/?ref=app
3 Answers
+ 1
https://docs.python.org/3/faq/programming.html#how-do-i-create-a-multidimensional-list
“The reason is that replicating a list with * doesn’t create copies, it only creates references to the existing objects”
a[0].append(4) line mutates the object that a[0] currently references to.
a[0] = [1] line makes a[0] now references to [1] (a[0] here acts as a lvalue)
a[1], a[2]... still reference to the original object.
0
It works as expected, so does []*n create n pointers to the same memory address where [] is stored ?
0
So why does append work in this weird way ? You can have a look at the edited code. The assignment is local but the append method isn't.