3

The following code

n = 3
matrix = [[0] * n] * n
for i in range(n):
    for j in range(n):
        matrix[i][j] = i * n + j 
print(matrix)

prints

[[6, 7, 8], [6, 7, 8], [6, 7, 8]]

but what I expect is

[[0, 1, 2], [3, 4, 5], [6, 7, 8]]

Why?

3 Answers 3

3

Note this:

>>> matrix = [[0] * 3] * 3
>>> [x for x in matrix]
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> [id(x) for x in matrix]
[32484168, 32484168, 32484168]
>>>

Three rows but only one object.

See the docs especially Note 2 about the s * n operation.

Fix:

>>> m2= [[0] * 3 for i in xrange(5)]
>>> [id(x) for x in m2]
[32498152, 32484808, 32498192, 32499952, 32499872]
>>>

Update: Here are some samples of code that gets an answer simply (i.e. without iter()):

>>> nrows = 2; ncols = 4
>>> zeroes = [[0 for j in xrange(ncols)] for i in xrange(nrows)]
>>> zeroes
[[0, 0, 0, 0], [0, 0, 0, 0]]
>>> ap = [[ncols * i + j for j in xrange(ncols)] for i in xrange(nrows)]
>>> ap
[[0, 1, 2, 3], [4, 5, 6, 7]]
>>>
Sign up to request clarification or add additional context in comments.

1 Comment

The docs says "...This often haunts new Python programmers...". True! But why this feature can be useful?
1

Try running matrix[0][0] = 0 after that. Notice it now becomes:

[[0, 7, 8], [0, 7, 8], [0, 7, 8]]

So it's changing all three at the same time.

Read this: http://www.daniweb.com/software-development/python/threads/58916

That seems to explain it.

3 Comments

Thanks Mk12 for the link. And I have the same question: whether this is a "feature" of Python or a "bug."?
It isn't something I expected, that's for sure. But it makes sense.
@user949952: The docs (see my answer) say that it takes a shallow copy of the sequence. So it's a feature.
1
>>> it = iter(range(9))
>>> [[next(it) for i in range(3)] for i in range(3)]
[[0, 1, 2], [3, 4, 5], [6, 7, 8]]

just replace 3 with n and 9 with n**2

Also (just answer the "why?"), you're making copies of the same list with multiplication and, therefore, modifying one of them will modify all of them.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.