Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reassigning row/list in a 2d list in python

I was trying to create an 2d list in python that was x + 1,y + 1 sized and had some initial values. Those initial values are that the first row contains the numbers 0 to 'x' and the first column contains the numbers 0 to 'y' (both inclusively)

Lets say x and y were 3 and 4.

So I went: listName = [range(0, x + 1)] * (y + 1);

This gives me a 2d list that has 5 rows and each row is a list with the numbers 0 to 3 giving 4 indexes on each row (4 columns):

[[0, 1, 2, 3], 
 [0, 1, 2, 3], 
 [0, 1, 2, 3], 
 [0, 1, 2, 3], 
 [0, 1, 2, 3]]

I understand that at this point I have a 2d array, but each row is an instance so if I changed any value in each row, all the rows would reflect that change. So to fix that I decided to set each row to a new unique list:

for row in listName:
    row = range(0, x + 1);

But I noticed that this seems to have no effect, my original list Even if I went:

for row in listName:
    row = ["A", "B", "C", "D"];

Printing before and after the assignment shows 'row' is getting changed, but outside the loop, I get my original list when I print it. Even though I've found another way to do what I want, I can't seem to figure out why this happens. Any ideas?

like image 556
mitim Avatar asked Nov 20 '25 17:11

mitim


1 Answers

Slice-assign in order to modify the existing list, instead of just rebinding the name.

row[:] = ...

Also, you're constructing it incorrectly.

listName = [range(0, x + 1) for z in range(y + 1)]
like image 197
Ignacio Vazquez-Abrams Avatar answered Nov 22 '25 15:11

Ignacio Vazquez-Abrams