Amazing Coder
Amazing Coder

Reputation: 31

Add integers of two lists of lists together

I am trying 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. Without using any third-party libraries (without using pandas for example).

It should work something like this:

>>> matrix1 = [[1, -2], [-3, 4]]
>>> matrix2 = [[2, -1], [0, -1]]
>>> add(matrix1, matrix2)
[[3, -3], [-3, 3]]

My current code:

list_3 = []


# Add function

def add(*args):
    for arg in args:
        for i in range(0, len(args)):
                list_3.append(arg[i - 1] + arg[i - 1] + arg[i - 1])
                print(f"Result: {list_3}")

My code does not work. Help would be appreciated.

Upvotes: 0

Views: 379

Answers (2)

Samwise
Samwise

Reputation: 71454

This is simple to do with a couple of nested comprehensions using zip:

>>> matrix1 = [[1, -2], [-3, 4]]
>>> matrix2 = [[2, -1], [0, -1]]
>>> [[a + b for a, b in zip(x, y)] for x, y in zip(matrix1, matrix2)]
[[3, -3], [-3, 3]]

or maybe using map and sum to build the inner lists:

>>> [list(map(sum, zip(x, y))) for x, y in zip(matrix1, matrix2)]
[[3, -3], [-3, 3]]

Upvotes: 6

BNilsou
BNilsou

Reputation: 895

You can iterate through the arguments, then iterate through the items of each arguments.

def add(*args):
    list_tmp = []
    for arg in args:
        for item in arg:
            list_tmp.append(item)
    return list_tmp

I also advise you to store the items in a local variable (list_tmp) and to return it: you can avoid a global variable.

Upvotes: 1

Related Questions