Why do I get "List index out of range" when trying to add consecutive numbers in a list using "for i in list"?
<p>Given the following list</p>
<pre><code>a = [0, 1, 2, 3]
</code></pre>
<p>I'd like to create a new list <code>b</code>, which consists of elements for which the current and next value of <code>a</code> are summed. It will contain <strong>1</strong> less element than <code>a</code>.</p>
<p>Like this:</p>
<pre><code>b = [1, 3, 5]
</code></pre>
<p>(from 0+1, 1+2, and 2+3)</p>
<p>Here's what I've tried:</p>
<pre><code>b = []
for i in a:
    b.append(a[i + 1] + a[i])
</code></pre>
<p>The trouble is I keep getting this error:</p>
<blockquote>
<p>IndexError: list index out of range</p>
</blockquote>
<p>I'm pretty sure it occurs because by the time I get the the last element of <code>a</code> (3), I can't add it to anything because doing so goes outside of the value of it (there is no value after 3 to add). So I need to tell the code to stop at 2 while still referring to 3 for the calculation.</p>