Why does append overwrite the list?

坚强是说给别人听的谎言 提交于 2020-01-30 11:41:33

问题


I was trying some questions from hackerrank and came across this question https://www.hackerrank.com/challenges/list-comprehensions/problem

I tried this solution

if __name__ == '__main__':
x = int(input())
y = int(input())
z = int(input())
n = int(input())
L = []
SL = []
for i in range(0, x + 1):
    for j in range(0, y + 1):
        for k in range(0, z + 1):
            if i + j + k != n:
                SL[:] = []
                SL.append(i)
                SL.append(j)
                SL.append(k)
                print(SL)
                L.append(SL)
print(L)

although SL had the right solution I can't append SL to the main list L for some reason, and apparently L.append(SL) overwrites the list L each time it it executed as it prints the last value of SL. Why does it happen? I tried using extend, but instead of making it a list of lists, it was created as just a list of integers. EDIT: Thank you all for the explanations!


回答1:


Indeed your code does not work, and it is due to the line SL[:] = []: it changes the content of the list referenced by SL. By doing this, you change all the elements of L, because you always append the list referenced by SL to L in the loop. Replacing with SL = [] will fix the problem, because in this case you create a new list without overwriting the previous one.
It could be fixed, and also be more readable and easier to debug (if needed) with the following suggestion:

L = []
for i in range(0, x + 1):
    for j in range(0, y + 1):
        for k in range(0, z + 1):
            if i + j != n and i + k != n and k + j != n and i + j + k != n:
                L.append([i, j, k])
print(L)

With x=1, y=2, z=3, n=4: it gives me the following output:

[[0, 0, 0], [0, 0, 1], [0, 0, 2], [0, 0, 3], [0, 1, 0], [0, 1, 1], [0, 1, 2], [0, 2, 0], 
 [0, 2, 1], [0, 2, 3], [1, 0, 0], [1, 0, 1], [1, 0, 2], [1, 1, 0],  [1, 1, 1], [1, 2, 0]]



回答2:


This line clears the list by deleting all its items. The list stays the same variable (same object), only its contents is modified:

SL[:] = []

Later in the code is this line (in a loop):

L.append(SL)

But SL is the same variable each time. All items in L refer to the same list SL. So when SL is modified, all items in L refer to the new contents of SL.

This can be fixed by creating a new list for each result.



来源:https://stackoverflow.com/questions/50533072/why-does-append-overwrite-the-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!