1

I am new to Python (and coding) and thought I had a reasonable grasp on the structure but I have been stuck on this one. I want to change the first value of a nested list and then update the value for the next position in the list (e.g., creating grid coordinates as nested lists).

p_d = 3

passes = 1
grid = []
row = []
column = [0, 0, 0]

while passes <= p_d:
    row.append(column)
    grid.append(row)
    passes += 1

for i in range(len(row)):
    column[i] = -(p_d - 1) / 2 + i

print(row)

The result is this:

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

But what I really need SHOULD be something like this:

[[-1.0, 0, 0], [0.0, 0, 0], [1.0, 0, 0]]
1
  • No, it shouldn't. You've appended the same list, column, to the outer list row, three times. So you should expect to see the same list three times... Commented Jun 13, 2017 at 4:55

2 Answers 2

1

By doing row.append(column) and grid.append(row), you are putting the same row and column objects into your matrix several times.

Instead, move the creation of row and column (e.g., the row = ... and column = ...) lines inside the loop so that you create new values on each iteration.

Sign up to request clarification or add additional context in comments.

Comments

0

You are appending the same list object to row when you do row.append(column) because column has been created only once globally. So changing any one column will change all the columns because they are the same list object. Same goes for rows

Move the line column = [0,0,0] and row = [] inside the for loop:

p_d = 3

passes = 1
grid = []

while passes <= p_d:
    row = []
    column = [0, 0, 0]
    row.append(column)
    grid.append(row)
    passes += 1


for i in range(len(grid)):
    grid[i][0][0] = -(p_d - 1) / 2 + i

print(grid)

2 Comments

You also need to move row = [] inside the loop, or you'll have the same problem with the rows.
thanks much, saves me tons of time banging my head against the wall!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.