broncosaurus broncosaurus -4 years ago 44
Python Question

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

Answer Source

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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download