How to find sum of list of lists using for-loop
<pre><code>prefer_indic = [[[0, 4, 6, 5, 45, 1], [2, 3, 5, 6, 7, 1]],[[0, 0.27, 6, 7, 32, 3], [0.01, 0.39, 0, 0, 0, 0]]]
</code></pre>

<p>I want to create a sum list that will add every value from every list of lists with each corresponding ones.
To be accurate i want: </p>

<p><code>sum = [[0+0, 4+0.27, 6+6, 5+7, 45+32, 1+3], [2+0.1, 3+0.39, 5+0, 6+0, 7+0, 1+0]]</code></p>

<p>I want to do it with a for loop so that i can use the same algorithm for bigger list of lists.I made the example simple to make it more readable. I have python 2.7 .</p>

<p>Use the <a href="https://docs.python.org/2/library/functions.html#zip" rel="nofollow"><code>zip()</code> function</a> to pair up elements from 2 or more lists, then use <a href="https://docs.python.org/2/library/functions.html#sum" rel="nofollow"><code>sum()</code></a> to add up the combined values:</p>

<pre><code>summed = [[sum(zipped) for zipped in zip(*column)] for column in zip(*prefer_indic)]
</code></pre>

<p>Note the <code>zip(*prefer_indic)</code> call, which <em>transposes</em> your matrix so that you pair up the 'columns' of your nested lists, not the rows.</p>

<p>If your lists are larger, it may be beneficial to using the <a href="https://docs.python.org/2/library/itertools.html#itertools.izip" rel="nofollow"><em>iterative</em> version of <code>zip</code></a>; use the <a href="https://docs.python.org/2/library/future_builtins.html#future_builtins.zip" rel="nofollow"><code>future_builtins.zip()</code> location</a> and your code is automatically forward-compatible with Python 3:</p>

<pre><code>try:
    from future_builtins import zip
except ImportError:
    # Python 3

summed = [[sum(zipped) for zipped in zip(*column)] for column in zip(*prefer_indic)]
</code></pre>

<p>Demo:</p>

<pre><code>&gt;&gt;&gt; from future_builtins import zip
&gt;&gt;&gt; prefer_indic = [[[0, 4, 6, 5, 45, 1], [2, 3, 5, 6, 7, 1]],[[0, 0.27, 6, 7, 32, 3], [0.01, 0.39, 0, 0, 0, 0]]]
&gt;&gt;&gt; [[sum(zipped) for zipped in zip(*column)] for column in zip(*prefer_indic)]
[[0, 4.27, 12, 12, 77, 4], [2.01, 3.39, 5, 6, 7, 1]]
</code></pre>

python python-2.7 for-loop sum