Python Morsel Week One

Posted on Mon 13 July 2020 in morsels

In an attempt to improve my abilities with Python I am starting to do Python Morsels.

The problem statement:

I'd like you to write a function that accepts two lists-of-lists of numbers and returns one list-of-lists with each of the corresponding numbers in the two given lists-of-lists added together. It should work something like this:

>>> matrix1 = [[1, -2], [-3, 4]]
>>> matrix2 = [[2, -1], [0, -1]]
>>> add(matrix1, matrix2)
[[3, -3], [-3, 3]]
>>> matrix1 = [[1, -2, 3], [-4, 5, -6], [7, -8, 9]]
>>> matrix2 = [[1, 1, 0], [1, -2, 3], [-2, 2, -2]]
>>> add(matrix1, matrix2)
[[2, -1, 3], [-3, 3, -3], [5, -6, 7]]

I wanted to just go through this as I normally would and then try to improve the solution. Here was my first attempt:

def add(list_of_lists_1, list_of_lists_2):
    # given two list of lists [[1,2,3], [4,5,6]] and [[1,1,1], [2,2,2],[3,3,3] add them together
    final_list_of_lists = []
    if len(list_of_lists_1) == len(list_of_lists_2):
        # go add each item of the lists together to create a new list
        for index, number_list in enumerate(list_of_lists_1):
            if len(final_list_of_lists) <= index:
                final_list_of_lists.append([])
            number_list_2 = list_of_lists_2[index]
            # for each item in the list add them with the same item index of the other list
            for i, item in enumerate(number_list):
                final_list_of_lists[index].append(
                    item + number_list_2[i]
                )
    return final_list_of_lists