What is the output of the following code?
for x in range(4):
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 .
And similarly in next step we add D to List L which should make L=[]
So when the for loop runs 2nd time with x=1
D becomes [0,1]
And L becomes [,[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,1],[0,1,2],[0,1,2,3]]
So at last when we give command print(L)
Shouldn't it print ????
But the answer was [0,1,2,3]
I think this would be the answer if the code looks like this
for x in range(4):
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]]
D = L = [ ]
D.append(x) // x = 0 makes
D = 
L.append(D) will add reference of D into L so L becomes []
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 which is [0,1,2,3]
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.
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
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:
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