problem with two-dimensional list/array

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • peachdot
    New Member
    • Aug 2010
    • 20

    problem with two-dimensional list/array

    hi,

    i've created a 2D list(ie: A=[]). i choose some of element from the list(ie: A[0][0],A[1][1],A[2][2]) and do simple add operations.

    Then i created another empty 2D list to store the result. but i wanted the result to be stored at a specific index (ie: at B=[0][0],B[1][1],B[2][2]).

    but i get an error."Error - list index out of range "

    here is my code...can anyone spot my mistake...

    Code:
    A=[]
    		for i in range(3):
    			A.append([])
    A[0]=(1,3,4,5)
    A[1]=(2,4,6,5)
    A[2]=(3,6,7,4)
    
    B=[]
    	  for j in range(3):
                 B.append([])
                 for i in range(3):
                     B[i][i]=2+A[i][i]
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    Your indentation is wrong, but I suspect it is a copy/paste problem.

    You did not initialize list B properly.
    Code:
    A=[]
    for i in range(3):
        A.append([])
    A[0]=(1,3,4,5)
    A[1]=(2,4,6,5)
    A[2]=(3,6,7,4)
     
    B=[[None for i in range(4)] for j in range(3)]
    
    for i in range(3):
        B[i][i]=2+A[i][i]
    Code:
    >>> B
    [[3, None, None, None], [None, 6, None, None], [None, None, 9, None]]
    >>>

    Comment

    • dwblas
      Recognized Expert Contributor
      • May 2008
      • 626

      #3
      Then i created another empty 2D list to store the result.
      You can use an intermediate list for this as well, unless I misunderstand.
      Code:
      A=[]
      A.append((1,3,4,5))
      A.append((2,4,6,5))
      A.append((3,6,7,4))
       
      B=[]
      for j in range(3):
          temp_list = []     ## starts as empty for each "j" loop
          for k in range(4):
              temp_list.append(2+A[j][k])
       
          B.append(temp_list)

      Comment

      Working...