Home > Mobile >  assignment in 2D array - Python
assignment in 2D array - Python

Time:11-22

I am new in Python. I am trying to assignment a variables in 2D array, I am using For-loop just for the first dimensional, the second dimensional i am assignmenting by myself:

A = [3, 4]
B = []

for i in range(len(A)):
B[i*2][0] = 5
B[i*2][1] = 6
B[i*2][2] = 7

B[i*2  1][0] = 10
B[i*2  1][1] = 10
B[i*2  1][2] = 10

I am expecting to see matrix B[4][3]:

B[0] = [5, 6, 7]

B[1] = [10, 10, 10]

B[2] = [5, 6, 7]

B[3] = [10, 10, 10]

but i am receiving this error:

Traceback (most recent call last):
File "E:\Python\assignment1_materials\ex1_student_solution.py", line 30, in <module>
B[i*2][0] = 5
IndexError: list index out of range

what I am making wrong?

CodePudding user response:

The issue is that B is an empty list. At the line for example,

B[i*2][0] = 5

You are trying to assign something to B[0][0] which does not exist, since B is currently [] (empty). There could be couple of ways to remedy this.

  1. Make sure the indices are there for assignment later on. That is, the index B[0][0] exists before hand, and then you can choose to assign that. You can do this by initializing it as :

    B = [[None]*4 for x in range(2*len(A))]

B will look like

[[None, None, None, None],
 [None, None, None, None],
 [None, None, None, None],
 [None, None, None, None]]

Then you can assign values to its indices.

  1. The other way is to do it in a lazy way. That is when you want to assign a value, then keep appending to B. (.append() will create a new index and assign your value to it).

It will look something like :

for i in range(len(A)) : 
    tmp = []
    tmp.append(5)
    tmp.append(6)
    tmp.append(7)
    B.append(tmp)

    tmp = []
    tmp.append(10)
    tmp.append(10)
    tmp.append(10)
    B.append(tmp)

CodePudding user response:

In this case, the array B is initialized as an empty 1-dimensional array. In order to initialize this to a 4x3 array, we need to do something like so:

B = [[0 for i in range(3)] for j in range(4)]

If we don't do so, then the code such as B[2][2] wouldn't work because there is no memory allocated to those indexes.

Thus the overall code would look something like so:

A = [3, 4]
B = [[0 for i in range(3)] for j in range(4)]

for i in range(len(A)):
  B[i*2][0] = 5
  B[i*2][1] = 6
  B[i*2][2] = 7

  B[i*2  1][0] = 10
  B[i*2  1][1] = 10
  B[i*2  1][2] = 10
  • Related