0

I have a list of two rows, and am just trying to replace one variable in one row, but it's changing the variable in both rows. Below is the code:

rowOfZeros_4cols = []

for i in range(0,4):
    rowOfZeros_4cols.append(0.)

twoRows = [rowOfZeros_4cols, rowOfZeros_4cols]

mat_Zeros = twoRows

mat_Zeros[0][2] = 1.

The output looks like:

[[0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 1.0, 0.0]] 

When I want it to look like:

[[0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 0.0]] 

What am I doing wrong? This seems like it should be pretty straight forward.

Thanks in advance, Eric

martineau
  • 119,623
  • 25
  • 170
  • 301
Eric
  • 41
  • 1
  • 4

1 Answers1

0

Here's the culprit:

twoRows = [rowOfZeros_4cols, rowOfZeros_4cols]

The two references to rowOfZeros_4cols are not two separate lists. That are the same object, referenced twice.

If you change it, it looks like "both rows" have changed. Instead, you're always changing the same row, only referring to it twice.

Generate a fresh row every time:

twoRows = [[0] * 4, [0] * 4]  # two independent lists of 4 zeros.
9000
  • 39,899
  • 9
  • 66
  • 104