Append list affecting all entries | Sololearn: Learn to code for FREE!
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

19th Oct 2021, 6:18 AM
Simone Appella
Simone Appella - avatar
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.
19th Oct 2021, 4:43 PM
Wei-Ting Yang 🇹🇼
0
It works as expected, so does []*n create n pointers to the same memory address where [] is stored ?
19th Oct 2021, 10:05 AM
Simone Appella
Simone Appella - avatar
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.
19th Oct 2021, 11:04 AM
Simone Appella
Simone Appella - avatar