I was trying some questions from hackerrank and came across this question https://www.hackerrank.com/challenges/list-comprehensions/problem
I tried this solution
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.
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]]