Thursday, October 14, 2010

[Py] Be careful when create multi-dimensional lists

I wrote a note about the creation of multi-dimensional lists in Python, when I had not yet encountered another problem which have emerged recently. The problem is about appending items to the multi-dimensional lists.

Consider the following example:

>>> A = [[]]*3
>>> A
[[], [], []]
>>> for i in range(3):
...    for j in range(3):
...        A[i].append(i+j)
...
>>> A
[[0, 1, 2, 1, 2, 3, 2, 3, 4], [0, 1, 2, 1, 2, 3, 2, 3, 4], [0, 1, 2, 1, 2, 3, 2, 3, 4]]

But what I really want is something like
A = [[0, 1, 2], [1, 2, 3], [2, 3, 4]]

My guess is that the creation approach doesn't create a list which contains three independent rows, but just create three rows which actually point to the same address or something like that.

The solution (perhaps not the best one) is to create the rows in the form of list comprehension:

>>> A = [[] for rows in range(3)]
>>> A
[[], [], []]
>>> for i in range(3):
...    for j in range(3):
...        A[i].append(i+j)
...
>>> A
[[0, 1, 2], [1, 2, 3], [2, 3, 4]]

No comments:

Post a Comment