Thursday, May 20, 2010

[Py] Multi-dimensional list

So far, the list in Python has bothered me a lot. I think it's because I do not understand it enough. These days I've been writing a little program to analyze some data, and encountered unexpected situations which almost got me down.

One unexpected situation was the multi-dimensional list, or the list of lists. The following page describes exactly what had troubled me:

(An Unofficial) Python FAQ Wiki (old link)
How do I create a multidimensional list?

This surprised me and made me thought again: ``Do I really know how to program in Python?'' The answer is definitely no. The low threshold to begin Python programming made me overestimate my understanding of it. Therefore, I told myself to learn more before stepping further.

Another situation surprised me is also about the list creation. The following test shows it:

>>> a = b = [[]]*3
>>> a[1] = 1
>>> b
[[], 1, []]

To assign values to list a also affects list b. To avoid this situation, you should create the lists separately.

>>> a = [[]]*3
>>> b = [[]]*3
>>> a[1] = 1
>>> b
[[], [], []]

No comments:

Post a Comment