0

I'm creating an array with nested arrays of arrays in which which all the elements are 1, such as:

[  [[1, 1], [1, 1]],
   [[1, 1], [1, 1]]  ]

When I run the following code I expect to have changed only a single element to 555, leaving all others as 1.

mesh = [[[1] * 2] * 2] * 2
mesh[0][0][1] = 555
print(mesh)

# same as above but trying to access a different element
mesh = [[[1] * 2] * 2] * 2
mesh[1][1][1] = 555
print(mesh)

So I want:

[[[1, 555], [1, 1]], [[1, 1], [1, 1]]]
[[[1, 1], [1, 1]], [[1, 1], [1, 555]]]

Instead, I'm getting the following:

[[[1, 555], [1, 555]], [[1, 555], [1, 555]]]
[[[1, 555], [1, 555]], [[1, 555], [1, 555]]]

So, not only does it not do what I expect, different code seems to produce the same output. Please explain why this is happening and, if possible, what code I should use instead. Thank you.

  • It has to do with the way you initialize the array. You will notice if you initialize it the standard way, mesh = [[[1, 1], [1, 1]], [[1, 1], [1, 1]]] you won't have this issue. – Sri Apr 16 '20 at 17:17
  • 1
    Basically when you use the multiplication operator when creating, you are still referencing the same instance of the initial list you create. So when you modify the first element, you are modifying the other elements that are also referencing that same element. See this post as well https://stackoverflow.com/questions/18933257/element-array-multiplication-vs-list-comprehension-initialization – Sri Apr 16 '20 at 17:19
  • @Sri You're right. When I type out the array as you have it works. Unfortunately, I'm trying to create an array of this size: [[[x] * 128] * 128] * 1000, which is is too big to type out – Harry Hudson Apr 16 '20 at 17:22
  • 1
    You can use a for loop and append values to the list. You do not need to manually create an array of that length. Are you familiar with how to do that? – Sri Apr 16 '20 at 17:23
  • @Sri Your second comment has answered my question. All sorted now - thanks! – Harry Hudson Apr 16 '20 at 17:35

1 Answers1

0

The problem comes from the array pointer (see C language). Only one 2D table in memory, the other tables point to this single table.

Solution:

mesh = [ [ [1 for x in range(2)] for i in range(2) ] for j in range(2) ]
mesh[0][0][1] = 555
print(mesh)
Martin13
  • 109
  • 9