broncosaurus
broncosaurus

Reputation: 25

Changing Value of One Index in a Nested List (Python)

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]]

Upvotes: 1

Views: 901

Answers (2)

Ishaan
Ishaan

Reputation: 886

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)

Upvotes: 0

BrenBarn
BrenBarn

Reputation: 251353

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.

Upvotes: 1

Related Questions