For-loop with range is only taking the last element

I have a 2D array of strings from which I delete certain elements (those containing the '#' char). When I print lista from inside the loop, it prints this:

['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']

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

['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']

Here's the loop:

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)

Upvotes: 1

Views: 498

Answers (2)

Julien
Julien

Reputation: 15071

Adding to niemmi's answer, what you need to do is:

    for i in range(0, len(programa)):
        lista = [] # creates a new empty list object alltogether
        ...

instead of

    for i in range(0, len(programa)):
        del lista[:]; # only clears the content, the list object stays the same

BTW, no ; needed in python.

Upvotes: 1

niemmi
niemmi

Reputation: 17263

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

Effectively you're doing following:

>>> lista = []
>>> temp = []
>>> lista.append('foo')
>>> temp.append(lista)
>>> temp
[['foo']]
>>> del lista[:]
>>> temp
[[]]
>>> lista.append('bar')
>>> temp.append(lista)
>>> temp
[['bar'], ['bar']]

Upvotes: 4

Related Questions