Why do I get a 'list index out of range' error for the below code using a for loop:
<p>Problem Statement: Given a nested list nl consisting of a set of integers, write a python script to find  the sum of alternate elements of the sub-lists.</p>

<pre><code>nl =  [[1,2,3],[4,5,6],[7,8,9],[10,11,12]]
sum = 0
n = 0
j=[]
for ele in nl:
    for i in ele:
        j.append(i)
        for a in j:
            sum = sum + j[n]
            n = n + 2
print(sum)
</code></pre>

<p>When I run this code, I get an error:</p>

<pre><code>Traceback (most recent call last):
File "C:\Users\ARUDRAVA\Contacts\Desktop\lists Assigment\assigment2.py",line 14, in &lt;module&gt;
sum = sum + j[n]
IndexError: list index out of range
</code></pre>

<p>Why is this error generated?</p>

<p>This is how it's usually done in Python:</p>

<pre><code>nl =  [[1,2,3],[4,5,6],[7,8,9],[10,11,12]]

total = sum(number for sublist in nl for number in sublist)
</code></pre>

<p>Don't name the variable <code>sum</code> - that would "hide" a built-in function. Exactly the function you need in fact.</p>

<hr>

<p>Anyway, the error in your code was here:</p>

<pre><code>sum = sum + j[n]
</code></pre>

<p>It should have been:</p>

<pre><code>sum = sum + a
</code></pre>

python python-3.x