0

I would like to write a function that calculates scalar sum of several vectors. It should take several lists as arguments eg.

def add_lists(x, y, z):
   # return sum of x, y, z

x = add_lists([1, 2],[2, 1],[3, 1])
# x returns [6, 4]

It is easy to do it for only two arguments, but how can I do it using *args if they are more than two, so that my add_lists will return [6, 4]?

Daniel
  • 521
  • 1
  • 7
  • 16
krakowi
  • 583
  • 5
  • 17

3 Answers3

4

You can use zip and *args:

def add_lists(*args):
    return [sum(x) for x in zip(*args)]

x = add_lists([1, 2],[2, 1],[3, 1])
# x is [6, 4]
Matias Cicero
  • 25,439
  • 13
  • 82
  • 154
  • 1
    This is the best and most general solution, and unlike other solutions here will automatically scale up if the length of all "vectors" changes. – DeepSpace Dec 07 '17 at 11:31
  • 1
    What I like here is that `zip(*args)` and `def add_lists(*args)` is using the `*` operator in two different ways: The first way is to demonstrate that multiple arguments can be passed through, whereas the second way is actually unpacking `args` into the `zip` function – TerryA Dec 07 '17 at 11:33
1

You can also do it this way:

def add_lists(*args):
    s1 = sum(i[0] for i in args)
    s2 = sum(i[1] for i in args)
    return [s1,s2]

res = add_lists([1, 2],[2, 1],[3, 1])
print(res)

Output:

[6, 4]
Vasilis G.
  • 7,556
  • 4
  • 19
  • 29
0

If I am understanding your question correctly, you wish to write a function that can take any amount of vectors and return the sum? Then yes, you would need to use *args like so:

def add_lists(*args):
    final_vector = [0, 0]
    for vector in args:
        final_vector[0] += vector[0]
        final_vector[1] += vector[1]
    return final_vector

Basically, treat args as a list - containing all the arguments passed through when you call the function.

TerryA
  • 58,805
  • 11
  • 114
  • 143