Why does append overwrite the list?

前端 未结 2 634
北恋
北恋 2021-01-27 08:06

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

I tried this solution

2条回答
  •  日久生厌
    2021-01-27 08:53

    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.

提交回复
热议问题