-2

I started learning Python and was trying an exercise, but I got struck:

x = 1
y = 1
z = 1
n = 2
list1 = []
list2 = []
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:
                list2.clear()
                list2.append(i)
                list2.append(j)
                list2.append(k)
                list1.append(list2)

print(list1)

Expected output:

[[0, 0, 0], [0, 0, 1], [0, 1, 0], [1, 0, 0], [1, 1, 1]]

Actual output:

[[1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1]]

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • 4
    `list1` contains the same list `list2` multiple times. Each reference to `list2` does not exist independently of the others; they are all one list. – khelwood Aug 17 '20 at 14:57
  • 1
    Move `list2 = []` inside the `if` statement so a new inner list is created for each sublist, otherwise you are reusing the same inner list over and over – Cory Kramer Aug 17 '20 at 14:58
  • 3
    Does this answer your question? [List of lists changes reflected across sublists unexpectedly](https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly) – superb rain Aug 17 '20 at 14:58

1 Answers1

0

Try replacing the inside of your for loop with list1.append([i, j, k]). The reason your way is not working is because when you append list2 is it only appending a shallow copy, so when you do list2.clear(), it is clearing the list you just appended in list1 as well. This would also work if you replace list2.clear() with list2 = []

iceagebaby
  • 76
  • 3