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>Your outer loops look like this:</p>

<pre><code>for ele in nl:
    for i in ele:
        j.append(i)
        # inner loop.
</code></pre>

<p>The first time the inner loop is reached, only one element has been appended to the list <code>j</code>. The second time the inner loop is reached, two elements have been appended to <code>j</code>, so the second time the loop is reached, <code>j</code> is <code>[1,2]</code>.  </p>

<p>It seems from your comment that you think that when the inner loop is reached, that <code>j</code> contains all 12 numbers from <code>nl</code>. That's not correct. Perhaps you meant for the "inner loop" to come after the two outside loops and not inside them.</p>

<p>Let's it is the second time that the inner loop is reached <code>j=[1,2]</code>, and suppose <code>n=0</code> (it might be larger than this but it can't be smaller)</p>

<p>Let's check the inner loop</p>

<pre><code>    for a in j:
        sum = sum + j[n]
        n = n + 2
</code></pre>

<p>Because j has two elements, it will loop twice:</p>

<p>The first time through the loop it adds <code>j[0]</code> to sum, and sets <code>n=0+2</code></p>

<p>The second time through the loop it tries to add <code>j[2]</code> to sum, which is a IndexError. </p>

<p>You will need to rethink the logic of your program. <em>Good Luck!</em></p>

python python-3.x