mkstlwtz
mkstlwtz

Reputation: 720

I am trying to initialize a matrix, but get the same row repeated

I am trying to initialize a matrix of a list of lists of characters.

aRow = [ '0', '0','0' ]
aGrid = [ aRow, aRow, aRow ]

After it appeared like one row repeated three times, I tried modifying the rows as follows and printing the result:

aGrid[1][0] = '1'
aGrid[2][0] = '2'

print( aGrid )

It looks like I am getting the third row three times.

[['2', '0', '0'], ['2', '0', '0'], ['2', '0', '0']]

Why?

Upvotes: 1

Views: 25

Answers (2)

user554538
user554538

Reputation:

In python, when you assign values you're really assigning references to the values. So this statement creates a list with the value ['0', '0', '0'] and assigns a reference to that value to aRow:

aRow = [ '0', '0','0' ]

And so this statement then creates a list with three references to the same list:

aGrid = [ aRow, aRow, aRow ]

In Python, lists are mutable values, so changes to the underlying value are reflected by all references to that value. So:

aGrid[1][0] = '1'

and:

aGrid[2][0] = '2'

Both change the first element of the underlying list that all three references in aGrid are referencing, and so the last change is the one you'll see.

Upvotes: 2

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799470

Because you are. You need to copy the object if you want the contents to be different.

aGrid = [aRow, aRow[:], aRow[:]]

Upvotes: 1

Related Questions