0

python: append question

a = [] b = [a,a,a] for x in b: n = len(x) # does n = 3 here? x.append(n). # does b = [a,a,a,3] now? print(b[0]) #outputs [0,1,2] How did we get this output?

11th Sep 2020, 6:42 PM
Solus
Solus - avatar
4 Réponses
+ 3
x=a=[] at first iteration, n=0 x.append(n) results in 0 appended to list [] and x and a both are pointing to the same list x=a=[0] at second iteration ,//as all the three a's are pointing to the same list , n=1 x.append(n) results in 1 appended to [0] resulting in [0,1] x=a=[0,1] at third iteration n=2 x.append(n) // results in [0,1,2] So since all a's are pointing to same list b[0] results in [0,1,2]
11th Sep 2020, 6:50 PM
Abhay
Abhay - avatar
+ 1
Solus the item(x) in list b is "a" which is pointing to [] , and x.append(n) results in mutation of original list , so [] is [0] ,not empty list [] ,at every iteration you are appending a number to the original list
11th Sep 2020, 7:06 PM
Abhay
Abhay - avatar
0
Abhay The the number of items (x) in list b doesn't change... So...why does the value of n increase with each iteration?
11th Sep 2020, 7:02 PM
Solus
Solus - avatar
0
You have stored a list reference in b list, not its values.. So same Refference will be copied to x in loop so all time you dealing with references, in one instance change will cause all refference point to a list cause change in a list... So in loop,, in first iteration a list is empty, len(x) means len(a) is 0, this you will appending to x so x refer to a, list appended 0... Now 2nd iteration, len(x) return 1, because 0 added previously... Next it return 2, because 0, 1 added before now a list added [0,1,2] In loop, it changing like a =[] b [a, a, a] After 1st iteration a = [0], b = [a,a,a] means =>[ [0], [0], [0]] After 2nd iteration a = [0, 1], b = [ [0,1], [0,1], [0,1]] After 3rd iteration a = [0, 1,2], b = [ [0,1,2], [0,1,2], [0,1,2]] So b[0] point list a so it will return [0,1,2]
11th Sep 2020, 9:07 PM
Jayakrishna 🇮🇳