-1

I have a array as follows, and I would like to change the value of the middle entry of the second row.

    array = [[0, 0, 0], 
             [0, 0, 0], 
             [0, 0, 0]]
    array[1][1] = 1

expected output:

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

however, it seems like the value of the whole column is changed:

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

Why does this not work? How do I just change the value of the entry that I want?

Thanks!

Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
Dawn Chen
  • 5
  • 2

2 Answers2

0

That is because you have not created your array the way you mentioned in the question. Instead you created it using * as:

>>> [[0]*3]*3
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]

In this case, all the nested list are point to the same reference of the list. Updating any value in list will reflect changes in all the list:

>>> array = [[0]*3]*3

>>> array[0][1] = 1 # updating 0th list
>>> array
[[0, 1, 0], [0, 1, 0], [0, 1, 0]]
#    ^          ^          ^  all 1 indexes updated

>>> array[1][0] = 2 # updating 1st list
>>> array
[[2, 1, 0], [2, 1, 0], [2, 1, 0]]
# ^          ^          ^     all 0 indexes updated

In order to fix this, create your array like:

>>> [[0]*3 for _ in range(3)]
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]

On performing same set of operations on this list, I get:

>>> array = [[0]*3 for _ in range(3)]

>>> array[0][1] = 1
>>> array  
[[0, 1, 0], [0, 0, 0], [0, 0, 0]]
#    ^   Only one value updated as expected

>>> array[1][0] = 2
>>> array
[[0, 1, 0], [2, 0, 0], [0, 0, 0]]
#            ^ again as expected      
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
  • Yes that's what I did, thank you so much! I didn't know that there's a difference between the different methods of declaring arrays. – Dawn Chen Oct 26 '16 at 00:51
  • @DawnChen: If it helped, then mark it as accepted (click tick button on the left of answer). Accepted answers act as a reference for others looking for the resolution of same issue in the future – Moinuddin Quadri Oct 26 '16 at 08:16
0

When I do it, I get the expected output.

I think the issue is likely that you didn't declare your array the way you have shown it above. I am going to guess you declared your array like this:

array = [[0, 0, 0]] * 3

What's happening here is you're creating 1 array row, [0, 0, 0] and setting array[0] = array[1] = array[2] = [0, 0, 0]. Since they're all pointing to one row, if you change one value in that row, that change will be visible across all 3 rows.

If you initialize the array with a list comprehension, you're creating a new row each time, and you will get your expected output:

array = [[0, 0, 0] for i in range(3)]