0
list1 = [[1,2],[3,4]]
list2 = [[2,3],[4,5]]

def function(a,b):
    answer =[]
    for i in range(len(a)):
        for j in range(len(a[0])):
            answer[i][j] = a[i][j] + b[i][j]
    return answer

print(function(list1,list2))

I'm new to python. I have no idea why I get this error.

IndexError: list index out of range
Gourav B
  • 864
  • 5
  • 17
Chicori
  • 11
  • 1
  • 1
    ```for j in range(len(a[0]))``` is taking the length of ```a[0]``` or the nested list –  Aug 12 '21 at 06:19

1 Answers1

3

The error is because of answer[i][j] = a[i][j] + b[i][j], since answer =[]

You are trying to assign the value by index to a list that is empty, so it throws IndexError

You either need to create the list with dummy values of the required size

list1 = [[1,2],[3,4]]
list2 = [[2,3],[4,5]]
def function(a,b):
    answer = [[0 for _ in _] for _ in a] #<---- zero values [[0, 0], [0, 0]]
    for i in range(len(a)):
        for j in range(len(a[0])):
            answer[i][j] = a[i][j] + b[i][j]
    return answer
print(function(list1,list2))

#output: [[3, 5], [7, 9]]

,Or you need to use append/extend mutable operations:

def function(a,b):
    answer = []
    for i in range(len(a)):
        row = []   #<---- create an empty list for inner list
        for j in range(len(a[0])):
            #answer[i][j] = a[i][j] + b[i][j]
            row.append(a[i][j] + b[i][j])   #<---Append each values to row
        answer.append(row)    #<--- Append row to answer list
    return answer
print(function(list1,list2))
#output: [[3, 5], [7, 9]]
ThePyGuy
  • 17,779
  • 5
  • 18
  • 45