Assign a list variable to a new variable results in two variables with the SAME list. Why. | Sololearn: Learn to code for FREE!
Nouvelle formation ! Tous les codeurs devraient apprendre l'IA générative !
Essayez une leçon gratuite
+ 1

Assign a list variable to a new variable results in two variables with the SAME list. Why.

Why this code results in appending a value to list a? So print(a) function outputs [2,4,6,8,5], while 5 was appended to list b? a =[2,4,6,8] b = a b.append(5) print(a)

14th Feb 2023, 6:54 AM
PholaX
5 Réponses
+ 5
I explain it in detail here (meant for reading - run it for seeing the examples): https://code.sololearn.com/c89ejW97QsTN/?ref=app
14th Feb 2023, 7:56 AM
HonFu
HonFu - avatar
+ 3
PholaX, yeah, that then becomes a practical problem: How can you write that function that it's the least likely to do damage? Handing over the object itself (the reference to it) gives the function quite a bit of power. So often it can be better to not hand over the... let's say list, but just have the function return the values *for* the list. Or, if a list has to be worked on, let the function work on a copy of the list. Do you have an example in mind? Might be interesting to consider the options.
14th Feb 2023, 10:33 PM
HonFu
HonFu - avatar
+ 1
Thank you, that was really helpful. So in Python, names of variables are just references to data in memory and by simple assignment we only get a new reference with another name. Therefore to create a new... hmm... "container" in memory we must explicitly say we want a new "object" using the constructor (or by assigning a new unique value). Right?
14th Feb 2023, 1:15 PM
PholaX
+ 1
PholaX, exactly. At least with mutable objects like lists and such we always need to know if we are refering to a similar object or that very object.
14th Feb 2023, 1:58 PM
HonFu
HonFu - avatar
+ 1
That's pretty hard, for example, when you have to pass a list as an argument to a function... But I also can see how it can be useful. Thank you again.
14th Feb 2023, 2:15 PM
PholaX