For-loop with range is only taking the last element
<p>I have a 2D array of strings from which I delete certain elements (those containing the '#' char). When I print <code>lista</code> from inside the loop, it prints this: </p>

<pre><code>['call', '_imprimirArray']
['movl', '24', '%2', '%3']
['movl', '%1', '%2']
['call', '_buscarMayor']
['movl', '%1', '4', '%3']
['movl', '$LC1', '%2']
['call', '_printf']
['movl', '$LC2', '%2']
['call', '_system']
['movl', '$0', '%2']
['movl', '-4', '%2', '%3']
</code></pre>

<p>But when I append each row to another 2D array, only the last element is assigned:</p>

<pre><code>['movl', '-4', '%2', '%3'],
['movl', '-4', '%2', '%3'],
['movl', '-4', '%2', '%3'],
['movl', '-4', '%2', '%3'],
['movl', '-4', '%2', '%3'],
['movl', '-4', '%2', '%3'],
['movl', '-4', '%2', '%3'],
['movl', '-4', '%2', '%3'],
['movl', '-4', '%2', '%3'],
['movl', '-4', '%2', '%3'],
['movl', '-4', '%2', '%3']
</code></pre>

<p>Here's the loop:</p>

<pre><code>def quitarEtiquetas(labels, programa):    
    lista = []
    temp = []

    for i in range(0, len(programa)):
        del lista[:]
        for j in range(0, len(programa[i])):
            if(programa[i][j].find('#') != -1):
                labels.append([programa[i][j].replace('#', ''), i])
            else:
                lista.append(programa[i][j])
        print(lista)
        temp.append(lista)
</code></pre>

<p>You're appending the same row many times to <code>temp</code> while just removing items from it on each iteration. Instead of <code>del lista[:]</code> just assign a new list to the variable: <code>lista = []</code> so that content in previously added rows doesn't get overwritten.</p>

<p>Effectively you're doing following:</p>

<pre><code>&gt;&gt;&gt; lista = []
&gt;&gt;&gt; temp = []
&gt;&gt;&gt; lista.append('foo')
&gt;&gt;&gt; temp.append(lista)
&gt;&gt;&gt; temp
[['foo']]
&gt;&gt;&gt; del lista[:]
&gt;&gt;&gt; temp
[[]]
&gt;&gt;&gt; lista.append('bar')
&gt;&gt;&gt; temp.append(lista)
&gt;&gt;&gt; temp
[['bar'], ['bar']]
</code></pre>

python arrays list python-3.x multidimensional-array