3

I was writing a programm in Python (2.5.4), and I realized that my code was not working because of something very unusual. I am going to give an example:

A = [[0]*2]*2

When I print A, I get:

[[0, 0], [0, 0]]

That is ok. But now I want to change the element in the first column and firts row. So I type:

A[0][0] = 1

But when I print A again, I get:

[[1, 0], [1, 0]]

However, I was expecting

[[1, 0], [0, 0]]

This is ruinning all my code. I want to know why this is happening and how I can fix it.

On the other hand, when I type:

B = [[0,0],[0,0]]

And make:

B[0][0] = 1

I get:

[[1, 0], [0, 0]]

This is even stranger! Aren't the two ways of implementing matrices equivalent? What if I wanted a 100x100 matrix with zeros? For this case, with a 2x2 matrix, I can type [[0, 0], [0, 0]]. But that is not a good solution.

Thiago
  • 133
  • 3
  • 1
    More generally, use numpy (http://www.numpy.org/) to do numerical computing instead of rolling your own. – Marcin May 11 '13 at 02:50

2 Answers2

7

This is because your list contains several references to a list.

>>> a = [0]
>>> l = [a,a]
>>> l[0][0] = "A"
>>> l
[['A'], ['A']]

We create a list and binded it to a. We then store two references to a in the list l via l=[a,a]. Then we manipulate one reference to a, and change it's first element to "A". Since a reference refers to a location in memory, my manipulating that reference (either element in l) we change the value in memory, hence affecting all other references to a.

enter image description here

This illustration, depicts the example above. The arrows represent a reference to a. They are the a's in l = [a,a]. When you change one of them, you change the value which they both point to. That interaction could be depicted like this:

enter image description here

We manipulate a via manipulating l[0] (l[0] is a reference to a), as such we can change the first element in a by changing l[0][0] (which would be the same as a[0]) to "A".

A depiction your list [[0]*2]*2 would look like this

enter image description here

HennyH
  • 7,794
  • 2
  • 29
  • 39
4

"What if you wanted a 100 x 100 matrix of zeros?"

Use a list comprehension:

[[0] * 100 for x in range(100)]
Radio-
  • 3,151
  • 21
  • 22