问题
I couldn't find anything matching my problem, so hopefully this wasn't already mentioned somewhere and I'm just too stupid to find it.
thelist = []
a = [0]
for i in range(5):
thelist.append(a)
print(thelist)
At this point, the program returns [[0], [0], [0], [0], [0]]
thelist[0].append(1)
print(thelist)
After appending this I would expect it to return the same but with the first element modified, like this:
[[0, 1], [0], [0], [0], [0]]
What actually happens, is that every element was modified in the same way and I get the following.
[[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]
I have found out, that if I replace the a in line 2 with the value of a, everything works fine. But why does this not work when I append a variable multiple times??
回答1:
When creating thelist, it's saving a reference to the same object (a) in each position. When you append to the first element, it's actually appending to a in all the "thelist" slots. What you need to do is a deep copy on the object during construction:
thelist = []
a = [0]
for i in range(5):
thelist.append(list(a))
print(thelist)
Then the following append will work as desired.
回答2:
a is an object that every item in the list is pointing to.
If you want every item in the list to be a different object (with the same value), you should create a new object before assigning it. the easiest way would be to do:
for i in range(5):
thelist.append(list(a))
The list function receives a list and return a new instance with the same inner values. So you won't be changing the entire array every time.
回答3:
thelist and a both are lists. So, inside the for loop you are appending a list into another list
Case 1: a is a list
thelist = []
a = [0]
for i in range(5):
thelist.append(a)
print(thelist)
[[0], [0], [0], [0], [0]]
Case 2: a is not a list but variable
thelist = []
a = 0
for i in range(5):
thelist.append(a)
print(thelist)
[0, 0, 0, 0, 0]
来源:https://stackoverflow.com/questions/23303934/list-index-changes-multiple-elements