2

Here is my code:

arr = [[0]*5]*6

print arr

for i in xrange(5):
    arr[0][i] = 'T'

print arr

Here is the output:

[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
[['T', 'T', 'T', 'T', 'T'], ['T', 'T', 'T', 'T', 'T'], ['T', 'T', 'T', 'T', 'T'], ['T', 'T', 'T', 'T', 'T'], ['T', 'T', 'T', 'T', 'T'], ['T', 'T', 'T', 'T', 'T']]

Why is this happening? I guess I'm more familiar with Java where iterating through arr[0][i] would only fill the top row of the array. And it makes no sense to me that it's different in Python since printing arr[i][j] (for some valid i, j) does in fact print the one item I expect at arr[i][j].

EDIT: In my defense about this being a duplicate, the question indicated as a duplicate of this one (and the question marked as a duplicate of that question) did not appear in my search whatsoever. Clearly I was typing in the wrong words to describe this phenomenon since I didn't know what it was called.

user124384
  • 400
  • 1
  • 9
  • 22
  • 2
    You're not filling a multidimensional array, you're filling an array of arrays. All those arrays happen to be the *same* array. There are just 6 of them. – Fengyang Wang Oct 13 '16 at 22:07
  • 1
    This is the same behaviour in Java too, except that in Java one frequently uses multidimensional arrays instead of arrays of arrays. – Fengyang Wang Oct 13 '16 at 22:08
  • Oh weird. I found this http://stackoverflow.com/questions/6667201/how-to-define-two-dimensional-array-in-python, which is I guess how I was supposed to do it. THANK YOU!!! – user124384 Oct 13 '16 at 22:08

0 Answers0