+ 1
what's the result of this codes? L,D=[],[] for x in range(4): D.append(x) L.append(D) print(L)
i thought the L should be [[0],[0,1],[0,1,2],[0,1,2,3]]. actually, the result is [[0,1,2,3],[0,1,2,3],[0,1,2,3],[0,1,2,3]]. so, how to understand the coding ?
4 odpowiedzi
+ 7
So, this is a classic mistake several people do
When you're appending D to L, in every step, the location of the memory cell that contains D is stored instead of the value stored in D at that instant of time.
So at the end, what you're doing is, you're creating a list L that has 4 elements which are mutable, hence have their own location/address.
Now, what the compiler does is, while printing your final list L, to print all the elements, it fetches the value stored in the memory cell containing the different particular elements.
Since what you ended up doing is feed the same location (i.e. the location of D) 4 times as different elements of L, the compiler fetches the same thing 4 times.
In this case the final value fetched is the final value of the list D, which is [0,1,2,3].
Hence, you end up with a string with the final value of D four times.
P.S. I'm very bad at explaining things but I hope I could help you to a certain degree :)
+ 5
A better way to what you wished to just do would be:
l=[]
def fun(x):
d=[i for i in range(x+1)]
l.append(d)
for i in range(4):
fun(i)
print(l)
This will work since everytime a new variable is called in a function, it gets assigned a new location whether a variable of the same name exists or not.
+ 1
Your are copying list D to list L.
At the end you have 4 times list D in list L.
But list D is always list D. It's a reverenz. And every time you change items in list D, by D. append(x), all reverences of list D will changed also.
Hope this is to understand 😉
+ 1
ANIMO UwU Thank you, my friend, your explanation is very good! it's very helpful to me. thanks a lot.👍👍👍