Reputation: 11
I'm doing this question on leetcode, why am I printing the correct result, but not getting the correct answer in leetcode? It seems if I do
nums[:]=list(endArray+frontArray)
Then it would work. I think it's some list assignment issue?
Upvotes: 0
Views: 151
Reputation: 70267
You've just discovered the difference between variables and their values. A variable in Python always points to a value. It references one but doesn't contain it.
nums = list(endArray+frontArray)
This snippet makes a new, unrelated list and assigns that list to nums
. The old list is still out there in memory somewhere unmodified. You just made a new one and assigned it to a local variable that's about to get deleted anyway.
nums[:] = list(endArray+frontArray)
This is an assignment to all positions ([:]
) of the current line. We're not making a new list; we're overwriting all of the values in the existing list. Anybody who held a reference to the previous list will see the changes in this case.
Upvotes: 1