How to remove list item within loop? [duplicate]

1

I'm trying to delete an item inside a loop. I already learned that it is not possible. I'm seeing how to implement a comprehensive list.

But I still do not understand how it works. I tried to do this:

result = [x for x in range(0, len(list)) if list[x][0] != 0 and list[x][1] != 0]

But it does not return the list without the positions I want, it only returns the indices.

Code below so far and giving error:

list = [
    [1,2],
    [3,4],
    [5,6],
    [0,0],
    [7,8]    
]

for x in range(0, len(list)):
    if list[x][0] == 0 and list[x][1] == 0:
        del list[x]

Error:

  

IndexError: list index out of range

Now I did this:

result = [list[x] for x in range(0, len(list)) if list[x][0] != 0 and list[x][1] != 0]

... And returned the list without the positions I wanted. Is that so?

    
asked by anonymous 21.05.2018 / 15:53

1 answer

4

First, do not use range(0, len(lista)) to scroll through a list in Python, just make item in lista which is more idiomatic, readable, and faster. Second, do not use the name list for variable; as it is the name of a Python native structure, you are overwriting the object and this can generate side effects.

If you want to remove all sublists that have both values equal to zero, just do:

filtrada = [item for item in lista if item != [0, 0]]

In this way, filtrada will be:

[[1, 2], [3, 4], [5, 6], [7, 8]]

To make it simpler to understand, the equivalent code would be:

filtrada = []
for item in lista:
    if item != [0, 0]:
        filtrada.append(item)

It generates the same result but requires 4 lines of code and is much less readable than list comprehension .

Another way, which could make the code more readable, is to use the filter function, which returns the instance of a generator that will iterate over the original list by applying the defined filter. For this example it would look like:

filtrada = filter(lambda it: it != [0, 0], lista)

So, being able to convert to a list with list(filtrada) or just iterate over the generator:

for item in filtrada:
    print(item)
    
21.05.2018 / 16:01