How to remove list item within loop?

Asked

Viewed 534 times

1

I’m trying to delete an item within a loop. I’ve heard it’s not possible. I’m seeing how to implement a comprehensive list.

But I still don’t understand how it works. I tried to do so:

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

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

Code below so far and that is 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’ve done so:

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

... And returned to the list without the positions I wanted. That’s how it is?

1 answer

5


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

If your intention is to remove all sub-lists 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 be simpler to understand, the equivalent code would be:

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

Generates the same result, but requires 4 lines of code and is much less readable than the comprehensilist on.

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

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

Thus, you can convert to a list with list(filtrada) or just iterate over the generator:

for item in filtrada:
    print(item)
  • A question that came, on a list [0, 1, 2, 3] the len() of it would be 4, right? in case when making a loop should use ... range(0, leng(...) - 1)? Since the first index is 0 and the last index is 3 and not 1 and 4

  • 2

    @Guilhermecostamilam Yes, the size would be 4, but the range(a, b) python sets a range [a, b[, I mean, it goes from a until b-1. For example, range(0, 4) would be [0, 1, 2, 3].

Browser other questions tagged

You are not signed in. Login or sign up in order to post.