-3

I'm guessing the problem happens because I append the same array multiple times and any changes made after are made to all the nested arrays. Is there a way to add them to an array and not get that to happen. For what I'm doing I to need about 500 different nested arrays, so doing it manually is a pain.

Output:

Before append

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

after append

[[0, 2, 0, 0], [0, 2, 0, 0], [0, 2, 0, 0], [0, 2, 0, 0]]

What I expected to happen after append:

[[0, 0, 0, 0], [0, 2, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]

Code:

testArray = []
nestedTestArray = []

def testarraynestedcreate():
    for countforloop1 in range(4):
        nestedTestArray.append(0)
        testArray.append(nestedTestArray)

testarraynestedcreate()
print(testArray)  # before change
testArray[1][1] = 2  # change element in array
print(testArray)  # after change )
martineau
  • 119,623
  • 25
  • 170
  • 301
PEEEZT
  • 19
  • 5

1 Answers1

0

You can use copy():

testArray.append(nestedTestArray.copy())

This way each list is independent from each other (and not a reference to the first one).

Miquel Escobar
  • 380
  • 1
  • 6