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!
This line clears the list by deleting all its items. The list stays the same variable (same object), only its contents is modified:
Later in the code is this line (in a loop):
But SL is the same variable each time. All items in
L
refer to the same listSL
. So whenSL
is modified, all items inL
refer to the new contents ofSL
.This can be fixed by creating a new list for each result.
Indeed your code does not work, and it is due to the line
SL[:] = []
: it changes the content of the list referenced bySL
. By doing this, you change all the elements ofL
, because you always append the list referenced bySL
toL
in the loop. Replacing withSL = []
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:
With x=1, y=2, z=3, n=4: it gives me the following output: