2D List

Chris Rebert clp2 at rebertia.com
Mon Oct 11 12:43:46 EDT 2010


On Mon, Oct 11, 2010 at 9:24 AM, Fasihul Kabir <rrockz09 at yahoo.com> wrote:
> a = [0]*5
>  for i in range(0, 4):
>     for j in range(0, i):
>         a[i].append(j)
>
> why the above codes show the following error. and how to overcome it.
>
> Traceback (most recent call last):
>   File "<pyshell#10>", line 3, in <module>
>     a[i].append(j)
> AttributeError: 'int' object has no attribute 'append'

`a` is a list of 5 zeroes (i.e. [0]*5 = [0, 0, 0, 0, 0]). Therefore,
a[i] is an integer with a value of 0; integers cannot be appended to
(the very concept makes no sense), hence your error.

If you want a list-of-lists, use a list comprehension. For example:
a = [[0]*5 for k in range(5)]
Which gives:
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]]

I am now obligated to link you to the following, which describes a
common related pitfall:
http://effbot.org/pyfaq/how-do-i-create-a-multidimensional-list.htm

Also, you probably want range(5) instead of range(0, 4) in your code.
A 5-element list has indices 0 up to and including 4. range(5)
produces the integers 0 to 4 inclusive. By contrast, range(0, 4)
produces the integers 0 to 3 inclusive.

If you want to perform mathematical matrix operations, you should use
NumPy (or did they rename it to Numeric? I've lost track).

Cheers,
Chris
--
http://blog.rebertia.com



More information about the Python-list mailing list