2D List

Gary Herron gherron at digipen.edu
Mon Oct 11 12:55:23 EDT 2010


On 10/11/2010 09:24 AM, Fasihul Kabir 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'
>

Well.... What are you trying to do with the append?  If you are trying 
to grow the list "a" beyond the original 5 zeros you put into it, then 
you need
   a.append(j)

If you are trying to build a list from the two loops, then don't 
pre-fill "a".  Rather start with an empty list
   a = []
and append to it
   a.append(j)

Don't know what you want, but there is usually not a need to pre-fill an 
array like this:  a=[0]*5 .   That looks more like declaring an array as 
in C or C++ or many other languages.  And I don't understand the the "5" 
in that.  Looking at your loops, I see that 6 passs through the inner 
loop are produced:

  for i in range(0, 4):
    for j in range(0, i):
      print i,j

1 0
2 0
2 1
3 0
3 1
3 2


In any case.
    Your "a" is a list, containing integers.
    a[i] indexes the list to produce an integer
    a[i].append(...) attempts to append something to an integer -- an 
operation that makes no sense.


-- 
Gary Herron, PhD.
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20101011/e6e0ac7c/attachment.html>


More information about the Python-list mailing list