问题
I am trying to use Python term to explain why the following happens, can somebody explain why tmp
becomes to [[1,2,3]]
not stay as [[1,2]]
?
arr = []
tmp = [1,2]
arr.append(tmp)
print arr # [[1,2]]
tmp.append(3)
print arr # [[1,2,3]]
回答1:
arr = []
is an empty list, and when you append tmp
to it via:
tmp = [1, 2]
arr.append(tmp)
You are putting tmp
in the arr
list, thus giving you arr = [tmp]
which can be expanded to arr = [[1,2]]
. But the neat thing here is that you maintain a reference to to the list, [1,2]
via the temp
variable. Thus, when you append temp
you are appending the same list that is in arr
.
For a bit further clarification, just because you are appending tmp
to arr
doesn't mean that the resulting list [[1,2]]
is all going to be one continuous block in memory. You are going to have the arr
list and the first element of arr
is going to be a pointer to the list tmp
.
回答2:
All the comments are great ones.
arr.append(tmp)
print arr # [[1,2]]
As you can see, the result is NOT:
print arr # [1,2]
So, arr
just holds the reference to tmp
array. If my guess is write you are looking for:
arr.extend(tmp)
print arr # [1,2]
More on difference between append vs. extend list methods in python
回答3:
That's because of both tmp
and arr[0]
points to the same object.
Just check it here, step by step:
http://www.pythontutor.com/visualize.html
First print statement Second print statement
You can manually check it by using id
built-in
>>> arr = []
>>> tmp = [1,2]
>>> arr.append(tmp)
>>> id(tmp)
4404123192
>>> id(arr[0])
4404123192
>>> assert id(tmp) == id(arr[0])
>>> tmp.append(3) # allocate more memory (if needs) and add '3' to object (list) with id 4404123192
>>> id(tmp)
4404123192
>>> id(arr[0])
4404123192
>>> print arr
[[1, 2, 3]]
来源:https://stackoverflow.com/questions/53055087/python-list-mutable