Skip to content Skip to sidebar Skip to footer

What Is Wrong With The Following Program Code, Attempting To Initialize A 4 X 4 Matrix Of Integers?

What is wrong with the following program code, attempting to initialize a 4 x 4 matrix of integers? How should the initialization be done? line = [0] * 4 matrix = [line, line, line

Solution 1:

Use a list comprehension:

>>>line = [[0]*4for _ in xrange(4)]>>>line
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]

Don't do this though:

>>>line = [[0]*4]*4>>>line
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]

The output looks same, but the problem here is all inner lists are actually the same object repeated 4 times:

>>>[id(x) for x in line]
[156931756, 156931756, 156931756, 156931756]

So, changing one of them is going to affect all:

>>> line[2][0] = 10
>>> line
[[10, 0, 0, 0], [10, 0, 0, 0], [10, 0, 0, 0], [10, 0, 0, 0]]

Same thing is applicable to your code:

>>>line = [0] * 4>>>matrix = [line, line, line, line]>>>[id(x) for x in matrix]
[158521804, 158521804, 158521804, 158521804]

If line contains only immutable object then you can change your code do:

>>>matrix = [line[:] for _ in xrange(4)]

But, if line contains mutable objects itself, then you'd have to use either copy.deepcopy or better create a new line object inside the list comprehension.

Solution 2:

you could use numpy for that if you want to perform computations on your matrix

import numpy as npzeros= np.zeros([4,4])

Solution 3:

The problem is:

>>>line = [0] * 4>>>matrix = [line, line, line, line]>>>matrix[0][0] = 5>>>matrix
[[5, 0, 0, 0], [5, 0, 0, 0], [5, 0, 0, 0], [5, 0, 0, 0]]

You have and array of references to the same vector.

Solution 4:

What is wrong here that you create a list of 4 references to line list. If you change any of sub-lists or line itself, you affect all sub-lists of matrix, since they (sub-lists) are essentially the same list Here is a little demonstration

In [108]: line = [0] * 4

In [109]: matrix = [line, line, line, line]

In [110]: line[1]=2

In [111]: matrix
Out[111]: [[0, 2, 0, 0], [0, 2, 0, 0], [0, 2, 0, 0], [0, 2, 0, 0]]

In [112]: matrix[1][3] = 4

In [113]: matrix
Out[113]: [[0, 2, 0, 4], [0, 2, 0, 4], [0, 2, 0, 4], [0, 2, 0, 4]]

In [114]: for row in matrix:
       .....:     print id(row)
       .....:     
    3065415660306541566030654156603065415660

Solution 5:

You need to do this:

matrix = [[0forrowinrange(4)] for col inrange(4)]

Post a Comment for "What Is Wrong With The Following Program Code, Attempting To Initialize A 4 X 4 Matrix Of Integers?"