+ 1

What is the output of the following code? #PYTHON

What is the output of the following code? L,D=[],[] for x in range(4): D.append(x) L.append(D) print(L[0]) What I think the answer should be... 1st if all L and D are both empty lists. Then we in the next line we say for x in range(4) so the range will be [0,1,2,3] . Now, with the value x=0 the value 0 should be added to the list and now the D is [0]. And similarly in next step we add D to List L which should make L=[[0]] So when the for loop runs 2nd time with x=1 D becomes [0,1] And L becomes [[0],[0,1]] And like this when the for loop runs for the last time with x= 3 D will become [0,1,2,3] And L will become [[0],[0,1],[0,1,2],[0,1,2,3]] So at last when we give command print(L[0]) Shouldn't it print [0]???? But the answer was [0,1,2,3] I think this would be the answer if the code looks like this L,D=[],[] for x in range(4): D.append(x) L.append(D) print(L[0]) In this L.append(D) is out of for loop so when the for loop is done with D=[0,1,2,3].. then L.append(D) will take the value[ [0,1,2,3]]

11th Jul 2019, 6:35 PM
Rohit Panchal
Rohit Panchal - avatar
5 Réponses
+ 4
Rohit Well, what happens if you add some more code to alter a after it was added to b? I believe b's content also changes. Try adding a.append(42) print(b) https://code.sololearn.com/cm1r361gZVQm/?ref=app
11th Jul 2019, 7:20 PM
ChrA
ChrA - avatar
+ 1
~ swim ~ ChrA thanks guys
11th Jul 2019, 7:50 PM
Rohit Panchal
Rohit Panchal - avatar
0
Hi. If you take the print command inside the loop an observer the content of complete L and complete D it appears that the insertion of D in L is not actually putting copies of D in L but reference (I think I remember that from the tutorial as well) So in fact the references in L always show the current contents of D. Hope that helps. Cheers. C
11th Jul 2019, 7:03 PM
ChrA
ChrA - avatar
0
ChrA Well if I understand your answer correct you are saying that L is just a reference to D. But doesn't append add an element to the list even if the element is list it self. I tried this: a=[1,2] b=[2,3] b.append(a) print(b) Output was [1,2,[2,3]] So I think I'm not able to understand what you are trying to say.. Sorry and thanks for you efforts and time... If possible please explain again.. Thank you
11th Jul 2019, 7:13 PM
Rohit Panchal
Rohit Panchal - avatar