How to remove an item from a list, iterating it in Python?

Suppose I have a list of numbers:

L = [1, 2, 3, 4, 5] 

How to remove an item, say 3, from a list while I repeat it?

I tried the following code, but it did not:

 for el in L: if el == 3: del el 

Any ideas?

Thanks, Boda Sido.

+4
source share
2 answers

It’s best to start constructively - create a new list of items that you want, instead of deleting those that you don’t have. For instance:.

 L[:] = [el for el in L if el != 3] 

comprehension of the list creates the desired list and assignment to the “list of the whole list”, L[:] , make sure that you are not just renaming the name, but completely replacing the contents, so the effects are equal to the “deletions” that you wanted to perform. It is also fast.

If you must make exceptions at all costs, a subtle approach may arise:

 >>> ndel = 0 >>> for i, el in enumerate(list(L)): ... if el==3: ... del L[i-ndel] ... ndel += 1 

Nowhere is as elegant, clean, simple, or well-executed as the listcomp approach, but it does its job (although its correctness is not obvious at first glance, and in fact I made a mistake before editing!). "at all costs" applies here; -).

Looping around indices instead of elements is another lower but workable approach for the “must do deletions” case, but remember to change the indices in this case ...:

 for i in reversed(range(len(L))): if L[i] == 3: del L[i] 

indeed, this was the main use case for reversed back, when we discussed the question of whether to add the built-in value reversed(range(... , which is not trivial to get without reversed , and cycling through the list in reverse order sometimes useful alternative

 for i in range(len(L) - 1, -1, -1): 

really easy to make a mistake; -).

However, the list I recommended at the beginning of this answer looks better and better when alternatives are considered, right? -).

+13
source
 for el in L: if el == 2: del L[el] 
-4
source

Source: https://habr.com/ru/post/1304070/


All Articles