Python error: Index out of range
<pre><code>seq_sum = []
for i in range(len(sequence)):
    seq_sum[i] = sequence[i] + inv_sequence[i]
print (seq_sum)
</code></pre>

<p>When I try to run this code it return an error: list assignment index out of range. How can I fix the problem?
sequence and inv_sequence are arrays of integers.</p>

<p><code>seq_sum[i]</code> will raise an <code>IndexError</code> as the <code>seq_sum</code> list is empty. You should use <code>append</code> instead:</p>

<pre><code>seq_sum = []
for i in range(len(sequence)):
    seq_sum.append(sequence[i] + inv_sequence[i])
print(seq_sum)
</code></pre>

<p>You can achieve the same result with a prettier code using list comprehension:</p>

<pre><code>seq_sum = [seq_elem + inv_elem for seq_elem, inv_elem in zip(sequence, inv_sequence)]
</code></pre>

<p>You could also use <code>map</code> but some would argue its readability:</p>

<pre><code>import operator
seq_sum = list(map(operator.add, sequence, inv_sequence))
</code></pre>

python python-3.x