IndexError in function
<pre><code>def AddVct(Vct1,Vct2,VctLen):
    Vct3 = []
    n=1
    while n &lt; VctLen:
        Vct3[n] = Vct1[n] + Vct2[n]
        n += 1
        print(Vct[n])
    return Vct3 
</code></pre>

<p>The program outputs:</p>

<p><code>IndexError: list assignment index out of range.</code></p>

<p>Could anyone tell me how to avoid this? Thanks in advance</p>

<p>You can't assign to a list element that doesn't exist. And since you start with an empty list, no elements exist in it. Generally, you would <code>append()</code> instead.</p>

<pre><code>Vct3.append(Vct1[n] + Vct2[n])
</code></pre>

<p>Or, you could initialize <code>Vct3</code> to be the size you want beforehand:</p>

<pre><code>Vct3 = [0] * VctLen + 1
</code></pre>

<p>Then the assignment you already have works fine.</p>

<p>Assuming you start with an empty list and use <code>append()</code>, list indices start at 0, so you should define <code>Vct3</code> as a single-element list so that the indices match between the input and output lists.</p>

<pre><code>Vct3 = [None]    # or whatever you want the first value to be
</code></pre>

<p>Or else initialize <code>n</code> to 0 instead of 1 if you want to consider all the elements of the lists.</p>

<p>In that case, however, it would be more Pythonic to use a list comprehension</p>

<pre><code>Vct3 = [a + b for (a, b) in zip(Vct1, Vct2)]
</code></pre>

<p>N. B. It's generally not necessary to pass in the length of a list as its own parameter. You can trivially get it using <code>len()</code>.</p>

python indexing