By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,660 Members | 1,102 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,660 IT Pros & Developers. It's quick & easy.

problem with two-dimensional list/array

P: 20
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...

Expand|Select|Wrap|Line Numbers
  1. A=[]
  2.         for i in range(3):
  3.             A.append([])
  4. A[0]=(1,3,4,5)
  5. A[1]=(2,4,6,5)
  6. A[2]=(3,6,7,4)
  7.  
  8. B=[]
  9.       for j in range(3):
  10.              B.append([])
  11.              for i in range(3):
  12.                  B[i][i]=2+A[i][i]
  13.  
  14.  
Sep 2 '10 #1

✓ answered by bvdet

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

You did not initialize list B properly.
Expand|Select|Wrap|Line Numbers
  1. A=[]
  2. for i in range(3):
  3.     A.append([])
  4. A[0]=(1,3,4,5)
  5. A[1]=(2,4,6,5)
  6. A[2]=(3,6,7,4)
  7.  
  8. B=[[None for i in range(4)] for j in range(3)]
  9.  
  10. for i in range(3):
  11.     B[i][i]=2+A[i][i]
Expand|Select|Wrap|Line Numbers
  1. >>> B
  2. [[3, None, None, None], [None, 6, None, None], [None, None, 9, None]]
  3. >>> 

Share this Question
Share on Google+
2 Replies


bvdet
Expert Mod 2.5K+
P: 2,851
Your indentation is wrong, but I suspect it is a copy/paste problem.

You did not initialize list B properly.
Expand|Select|Wrap|Line Numbers
  1. A=[]
  2. for i in range(3):
  3.     A.append([])
  4. A[0]=(1,3,4,5)
  5. A[1]=(2,4,6,5)
  6. A[2]=(3,6,7,4)
  7.  
  8. B=[[None for i in range(4)] for j in range(3)]
  9.  
  10. for i in range(3):
  11.     B[i][i]=2+A[i][i]
Expand|Select|Wrap|Line Numbers
  1. >>> B
  2. [[3, None, None, None], [None, 6, None, None], [None, None, 9, None]]
  3. >>> 
Sep 2 '10 #2

Expert 100+
P: 624
Then i created another empty 2D list to store the result.
You can use an intermediate list for this as well, unless I misunderstand.
Expand|Select|Wrap|Line Numbers
  1. A=[]
  2. A.append((1,3,4,5))
  3. A.append((2,4,6,5))
  4. A.append((3,6,7,4))
  5.  
  6. B=[]
  7. for j in range(3):
  8.     temp_list = []     ## starts as empty for each "j" loop
  9.     for k in range(4):
  10.         temp_list.append(2+A[j][k])
  11.  
  12.     B.append(temp_list) 
Sep 3 '10 #3

Post your reply

Sign in to post your reply or Sign up for a free account.