Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Behaviour of 2D array
#2
The problem is how you create it on this line

torus = [[0] * MAXHORZ] * MAXVERT
lists are mutable and you populate with same object, thus when you update one, it is reflected elsewhere

rows = 3
cols = 4

spam = [[0] * cols] * rows
print(spam)
print([id(row) for row in spam])
spam[0][0] = 1
print(spam)
print('-----------------------')
eggs = [[0] * cols for _ in range(rows)]
print(eggs)
print([id(row) for row in eggs])
eggs[0][0] = 1
print(eggs)
Output:
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] [12470912, 12470912, 12470912] [[1, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0]] ----------------------- [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] [13534272, 13534312, 13534152] [[1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Messages In This Thread
Behaviour of 2D array - by SimonB - Jan-21-2021, 09:56 AM
RE: Behaviour of 2D array - by buran - Jan-21-2021, 10:00 AM
RE: Behaviour of 2D array - by SimonB - Jan-21-2021, 10:34 AM
RE: Behaviour of 2D array - by buran - Jan-21-2021, 10:42 AM
RE: Behaviour of 2D array - by SimonB - Jan-21-2021, 11:41 AM
RE: Behaviour of 2D array - by buran - Jan-21-2021, 12:41 PM
RE: Behaviour of 2D array - by SimonB - Jan-21-2021, 01:29 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  logger behaviour setdetnet 1 932 Apr-15-2023, 05:20 AM
Last Post: Gribouillis
  can someone explain this __del__ behaviour? rjdegraff42 1 774 Apr-12-2023, 03:25 PM
Last Post: deanhystad
  Asyncio weird behaviour vugz 2 1,325 Apr-09-2023, 01:48 AM
Last Post: vugz
  Weird behaviour using if statement in python 3.10.8 mikepy 23 3,872 Jan-18-2023, 04:51 PM
Last Post: mikepy
  Generator behaviour bla123bla 2 1,152 Jul-26-2022, 07:30 PM
Last Post: bla123bla
  Inconsistent behaviour in output - web scraping Steve 6 2,642 Sep-20-2021, 01:54 AM
Last Post: Larz60+
  Adding to the dictionary inside the for-loop - weird behaviour InputOutput007 5 2,812 Jan-21-2021, 02:21 PM
Last Post: InputOutput007
  strange behaviour- plotting nathan_Blanc_Haifa 0 1,526 Dec-27-2020, 01:37 PM
Last Post: nathan_Blanc_Haifa
  OOP behaviour problem JohnB 3 2,466 Aug-18-2020, 07:51 PM
Last Post: JohnB
  understanding basic loop behaviour vinci 5 2,976 Feb-11-2020, 09:53 PM
Last Post: vinci

Forum Jump:

User Panel Messages

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