Search code examples
pythonfor-loopdel

Python: Using del in for loops


I was iterating through a list with a for loop, when I realized del seemed to not work. I assume this is because i is representing an object of the for loop and the del is simply deleting that object and not the reference.

And yet, I was sure I had done something like this before and it worked.

alist = [6,8,3,4,5]  

for i in alist:  
    if i == 8:  
        del i  

In my code its actually a list of strings, but the result is the same: even though the if conditional is satisfied, deleting i has no effect.

Is there a way I can delete a number or string in this way? Am I doing something wrong?

Thanks.


Solution

  • Your idea as to why you are seeing that behavior is correct. Hence, I won't go over that.

    To do what you want, use a list comprehension (it is available in the old python2 as well) to filter the list:

    >>> alist = [6,8,3,4,5]
    >>> [x for x in alist if x != 8]
    [6, 3, 4, 5]
    >>> alist = [6,8,8,3,4,5]
    >>> [x for x in alist if x != 8]
    [6, 3, 4, 5]
    >>>
    

    This approach is also a lot more efficient than a for-loop.