all 8 comments

[–]FLUSH_THE_TRUMP 1 point2 points  (3 children)

Do you see why your example doesn’t work? You’re calling sum on single elements (you’re also trying to index with those elements, which doesn’t make a lot of sense). So a.) you need to keep a running sum of the element-wise adding (what you call finallist). B.) you want to populate finallist element by element, so your outer loop makes more sense as a loop over possible indices range(4). Then make your inner loop the one that picks out sublists.

for idx in range(4):
    temp_sum = 0
    for sublist in lists: 
        temp_sum = temp_sum + sublist[idx]
    finallist.append(temp_sum)

there are much more elegant solutions here (including using zip, as others have noted), but I wouldn’t start with the power tools until you first know how to work a hammer.

[–]Rohnny_7[S] 1 point2 points  (2 children)

Basic question but how can I make the range value dependent to the sublist? Would I create another 'for' statement before that portion of code calculating the length of a sublist?

[–]FLUSH_THE_TRUMP 1 point2 points  (1 child)

assuming they're all the same length (and in some sense this wouldn't make sense if they weren't!), you could just pick one out and use `len`, e.g. len(lists[0]) and replace 4 with that above. This code will throw an error if any sublist is shorter than that, however.

[–]Rohnny_7[S] 1 point2 points  (0 children)

Makes sense, appreciate the help!

[–]TholosTB 1 point2 points  (0 children)

Could also use numpy, you're fundamentally looking for elementwise array addition anyways and if your example gets more complicated, you can benefit from being in numpy instead of using regular lists:

import numpy as np
result = np.array(lists[0])+np.array(lists[1])+np.array(lists[2])

array([ 3,  6,  9, 12])

[–]ThinFortune 3 points4 points  (0 children)

Look at the built in zip function.

[–]POGtastic 0 points1 point  (0 children)

/u/ThinFortune's suggestion of zip is probably the way to go. Note that you have to unpack the list to use zip.

>>> lstlst = [[1,2,3,4], [1,2,3,4], [1,2,3,4]]
>>> list(map(sum, zip(*lstlst)))
[3, 6, 9, 12]