+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]]

7/11/2019 6:35:18 PM

Rohit

5 Answers

New Answer

+4

Rohit D = L = [ ] D.append(x) // x = 0 makes D = [0] L.append(D) will add reference of D into L so L becomes [[0]] now D.append(1) will add 1 to D D = [0,1] but since L contains the reference to D, the value of D in L also becomes [0,1] so L is now [[0,1]] now you explicitly add current D in L again so L becomes L = [[0,1], [0,1]] by the time your loop ends L = [[0,1,2,3], [0,1,2,3], [0,1,2,3], [0,1,2,3] ] Then you print L[0] which is [0,1,2,3]

+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

+1

~ swim ~ ChrA thanks guys

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

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