Python Forum
Can't modify a simple matrix
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Can't modify a simple matrix
#3
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
Lewkiy likes this post
Reply


Messages In This Thread
Can't modify a simple matrix - by Lewkiy - Feb-01-2023, 11:33 PM
RE: Can't modify a simple matrix - by Larz60+ - Feb-02-2023, 02:39 AM
RE: Can't modify a simple matrix - by deanhystad - Feb-02-2023, 04:19 AM
RE: Can't modify a simple matrix - by Lewkiy - Feb-05-2023, 02:59 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Check if two matrix are equal and of not add the matrix to the list quest 3 887 Jul-10-2023, 02:41 AM
Last Post: deanhystad
  How to multiply a matrix with herself, until the zero matrix results peanutbutterandjelly 3 3,411 May-03-2021, 06:30 AM
Last Post: Gribouillis
  Simple Matrix Assignment m_llaa 10 4,743 Aug-05-2019, 09:35 AM
Last Post: m_llaa
  matrix from matrix python numpy array shei7141 1 3,740 Jan-16-2017, 06:10 PM
Last Post: micseydel

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020