Home > OS >  Adding first value together from multiple lists
Adding first value together from multiple lists

Time:12-11

I am trying to add the first values together in a series of lists then add the second values together from a series of lists and so on.

for example:

a=[10,20,30,40,50]
b=[60,70,80,90,100]
c=[110,120,130,140,150]

so as a result I want

180, 210,240, 270, 300

the code I have so far is:

total = 0
for I in range (0,a)
total = total  a[I] b[I] c[I]
return total

CodePudding user response:

Use zip to get the first element of each list, and then sum them:

>>> a=[10,20,30,40,50]
>>> b=[60,70,80,90,100]
>>> c=[110,120,130,140,150]
>>> [sum(t) for t in zip(a, b, c)]
[180, 210, 240, 270, 300]

CodePudding user response:

Use the sum and zip functions with a simple list comprehension:

total = [sum(i) for i in zip(a,b,c)]

Or iterate over the indexes:

total = []
for i in range(len(a)):
    total.append(a[i]   b[i]   c[i])

total has to be a list and you have to append to it on each iteration.

CodePudding user response:

total = 0
for I in range (0,a):
    total = total  a[I] b[I] c[I]
return total

So, you have a few issues here with your code.

  1. You can't use range(0,a). a is list and not an integer. You would have to use the length of list, or len(a).

  2. You also aren't supposed to use capital letters as variables, unless they're constants variables, according to PEP8 standards.

  3. You're trying to return data that isn't inside a function. That won't work. You could do something like:

def add_vals_from_lists(a,b,c):
    total = 0
    for i in range(len(a)):
        total  = sum([a[i], b[i], c[i]])
        # The above is a much cleaner way to write total = total  a[I] b[I] c[I]
    return total

a=[10,20,30,40,50]
b=[60,70,80,90,100]
c=[110,120,130,140,150]

add_vals_from_lists(a,b,c)

Or, you could merely print(total) instead of using return total.

But, this will simply add everything to total returning 1200, not what you want.

As Samwise and Pedro noted, you can simply write this in a list-comprehension. [sum(t) for t in zip(a, b, c)]

zip() - Iterate over several iterables in parallel, producing tuples with an item from each one. For each of these tuples, (10,60,110) for the first one, the list-comprehension will sum() each one. Resulting in a list of [180, 210, 240, 270, 300].

  • Related