Frank Cheng
Frank Cheng

Reputation: 6186

What's the difference between these two ways of initializing an array?

matrix = [[0]*1005]*1005

and

matrix = [[0 for _ in range(1005)] for _ in range(1005)]

I found if i using the former to initial array, and run matrix[1][1] = 1 it will set the second column in every row to 1. And the second performed as i wished. I can't figure out why?

Upvotes: 1

Views: 110

Answers (2)

Jakob Bowyer
Jakob Bowyer

Reputation: 34688

Just to expand on whats already been said

a = [[0]] * 5
print a # [[0], [0], [0], [0], [0]]
a[0][0] = 1
print a # [[1], [1], [1], [1], [1]]

Upvotes: 3

Ry-
Ry-

Reputation: 224877

[[0] * 1005] * 1005 will create an array of 1005 references to an array with 1005 zeroes. They're all the same reference, and so changing one will change all the others. You can shorten your working code to this, though:

matrix = [[0] * 1005 for _ in range(1005)]

This is pretty much the only warning anybody ever gives you about the list multiplication syntax, actually :)

Upvotes: 8

Related Questions