Python Forum
Can't modify a simple matrix - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Can't modify a simple matrix (/thread-39338.html)



Can't modify a simple matrix - Lewkiy - Feb-01-2023

I'm a beginner in python and I can't understand why this doesn't work like seriously, i really tried. You can see the result of the function on the left, it modify a whole column, i only want to modify one 0 here. Furthermore, the blank matrix (SiteVierge2d) is modified, why ? I made a copy.

My code:

[attachment=2230]

SiteVierge2d=[[0]*(8)]*(5) #Le site vierge
def batiment2d(S,b,Origin,T):
    M=S[:]
    x0,y0=Origin
    l,k=T
    for i in range(x0,x0+l):
        for j in range(y0,y0+k):
            M[i][j]=b
    return M
print(batiment2d(SiteVierge2d,'t',(1,1),(2,1))) 
My goal is to make a function that modify the matrix in a form of a rectangle of 'b' (instead of 0). The origin point of the rectangle is x0,y0 and the length and wideness is l,k (but here in the image, everything is just 1), here is what i mean : [attachment=2231]

Thx for the help and sorry if this has already been answered somewhere because I didn't find it


RE: Can't modify a simple matrix - Larz60+ - Feb-02-2023

I'd suggest embedding print statements to show the intermediate values, or
if you have one available, the debugger in your IDE.


RE: Can't modify a simple matrix - deanhystad - Feb-02-2023

I don't think this does what you think.
SiteVierge2d=[[0]*(8)]*(5)
To start with, the parenthesis have no effect here. The code runs the same with or without.

More importnatly, SiteVierge2d[0] is the same list as SiteVierge2d[1] and SiteVierge2d[2]... You can see that if you look at the object ID's. All 5 lists in SiteVierge2d are the same object.
SiteVierge2d=[[0]*(8)]*(5)
print(*map(id, SiteVierge2d))
Output:
1776206706304 1776206706304 1776206706304 1776206706304 1776206706304
It is the same as if you wrote this:
zeros = [0] * 8
SiteVierge2d = [zeros] * 5
I think you want to do something like this:
SiteVierge2d = [[0]*8 for _ in range(5)]
print(*map(id, SiteVierge2d))
2218135596032 2218135268288 2218135123136 2218135124096 2218135599936
Now each of the lists in SiteVierge2d are different lists because [0] * 8 was executed 5 times.

I don't think this does what you think either:
M=S[:]
This does not make a deep copy. The lists in M are the same lists in S. If you set M[1][2] = 3 then S[1][2] == 3. If you want M to be a new 2D array with the same values as S, you need to do a deep copy.

https://docs.python.org/3/library/copy.html


RE: Can't modify a simple matrix - Lewkiy - Feb-05-2023

Thank you very much, it seems to work well !