This is a pretty good use case for zip
.
>>> list1 = [1,2,3,4,5]
>>> list2 = [1,1,1,4,1]
>>> list3 = [1,22,3,1,5]
>>> list4 = [1,2,5,4,5]
>>> [sum(x) for x in zip(list1, list2, list3, list4)]
[4, 27, 12, 13, 16]
or if you have your data as a list of lists instead of separate lists:
>>> data = [[1,2,3,4,5], [1,1,1,4,1], [1,22,3,1,5], [1,2,5,4,5]]
>>> [sum(x) for x in zip(*data)]
[4, 27, 12, 13, 16]
similarly, if you store your data as a dict
of lists, you can use dict.itervalues()
or dict.values()
to retrieve the list values and use that in a similar fashion:
>>> data = {"a":[1,2,3], "b":[3,4,4]}
>>> [sum(x) for x in zip(*data.itervalues())]
[4, 6, 7]
Note that if your lists are of unequal length, zip
will work up till the shortest list length. For example:
>>> data = [[1,2,3,4,5], [1,1], [1,22], [1,2,5]]
>>> [sum(x) for x in zip(*data)]
[4, 27]
If you wish to get a result that includes all data, you can use itertools.izip_longest
(with an appropriate fillvalue
). Example:
>>> data = [[1,2,3,4,5], [1,1], [1,22], [1,2,5]]
>>> [sum(x) for x in izip_longest(*data, fillvalue=0)]
[4, 27, 8, 4, 5]