+ 2

Don't understand a part in code with append()

I have this python code: https://code.sololearn.com/cgUc8iACeWHc/?ref=app a, b = [], [] print("a:", a, "b:", b) for x in range(2): print("x:", x) print("a:", a) a.append(x) print("after a.append(x) a:", a) print("b:", b) b.append(a) print("after b.append(a) b:", b) After the first iteration of the loop with x = 0 the values are a = [0] and b = [[0]]. In the second iteration with x = 1 the value of a = [0,1] Up to this point I totally understand it. But now even before the execution of b.append(a) the value of b = [[0,1]]. But why? I would expect that it is still [[0]] because we have not executed a command regarding b in the second iteration of the loop. At the end b = [[0, 1], [0,1]]. I would expect [[0], [0,1]].

9th Jul 2022, 12:03 AM
Niels F 🇩🇪 <html challenger>
Niels F 🇩🇪 <html challenger> - avatar
7 Respuestas
+ 6
Niels Ferber , what happens by appending the list 'a' to list 'b' is that it does not really uses the values of 'a', but a reference to that list. this means that whatever value you append to 'a', will also be shown in list 'b'. using the id() function we can see the memory adress of the object: id(a)=478120223040 id(b)=478120222976, id(b[0])=478120223040 so you can see that list 'a' has a different id than list 'b', but the nested list inside 'b' has the same id as list 'a'. to avoid this, we have to use copy() or deepcopy() from copy import copy ... b.append(copy(a)) ... now the result as you have expected it: [[0], [0,1]] you can read more about this here: copy — Shallow and deep copy operations¶ https://docs.python.org/3.8/library/copy.html#module-copy
9th Jul 2022, 5:56 PM
Lothar
Lothar - avatar
+ 6
Niels Ferber , that is what the documentation says: Assignment statements in Python do not copy objects, they create bindings between a target and an object.
9th Jul 2022, 8:26 PM
Lothar
Lothar - avatar
+ 3
Sousou Thanks for your reply. I understand is now. With b.append(a) it does not append the list b with the value of a. Instead it appends the list b with the variable a itself. Therefore, when the value of variable a changes, the value of b changes automatically.
9th Jul 2022, 12:26 AM
Niels F 🇩🇪 <html challenger>
Niels F 🇩🇪 <html challenger> - avatar
+ 1
Maybe b.append(a.copy()) instead of b.append(a) will do what you want
9th Jul 2022, 12:16 AM
Sousou
Sousou - avatar
+ 1
Lothar In the list b is now a pointer to variable a. Or what is the term for it in Python?
9th Jul 2022, 6:32 PM
Niels F 🇩🇪 <html challenger>
Niels F 🇩🇪 <html challenger> - avatar
0
Lothar Here is my corrected code that does what I had expected: https://code.sololearn.com/cHoiqDHS7xlR/?ref=app Instead of b.append(a) I use b.append(a.copy()) An import of an additional library is not necessary.
10th Jul 2022, 5:50 AM
Niels F 🇩🇪 <html challenger>
Niels F 🇩🇪 <html challenger> - avatar
0
Plz help me
10th Jul 2022, 9:34 AM
Vikesh Gangale
Vikesh Gangale - avatar