How can I use a for iterator as a function parameter in Python?

I'm trying to call a function that creates matrices from user input, but it says that i haven't defined something.

lstA = []
lstB = []
lstC = []

def get_list(data):
    lst = []
    for i in range(4):
        aux = []
        for j in range(4):
            aux.append(data)
        lst.append(aux)
    return lst

lstA = get_list(int(input(f'A i[{i}] j[{j}]: ')))
lstB = get_list(int(input(f'B i[{i}] j[{j}]: ')))
lstC = get_list(lstA[i][j] + lstB[i][j])

The program should take two 4x4 matrixes from user, by putting each informed number inside the lstA[i][j] and lstB[i][j].

Finally, lstC is used to sum A and B.

Error message:

Traceback (most recent call last):
  File "<string>", line 13, in <module>
NameError: name 'i' is not defined

[Program finished]

How can I solve this?

1 answer

  • answered 2019-11-14 05:11 smac89

    To read the data into the matrices, make a function like this:

    def get_lst():
      mat = [[]] * 4
      for i in range(4):
        mat[i] = [0] * 4
        for j in range(4):
          mat[i][j] = int(input(f'mat[{i}][{j}]: '))
      return mat
    

    This function will ask the user for input for each element of the matrix and populate that position with what the user entered.

    Now this is how you use it:

    lstA = get_lst()
    lstB = get_list()
    

    As for summing the elements of the matrices, refer to this answer