Fwd: PYTHON BUG. deleting elements of list.

Peter Otten __peter__ at web.de
Wed Sep 9 02:37:57 EDT 2020


Mats Wichmann wrote:

> On 9/7/20 5:01 PM, Driuma Nikita wrote:
> 
> 
>      _list = list(range(50))
>      for i, el in enumerate(_list):
>          del _list[i]
>      print(_list)
> 
> 
> Don't change the the list while you are iterating over it, it messes up
> the iteration. It's not "randomly deleting", it's when next is called to
> fetch the next item, the list has changed.
> 
> One workaround is to iterate over a copy. For example here's using
> slicing to create a new list to iterate over:
> 
>     for i, el in enumerate(_list[:]):
>          del _list[i]

As Richard says, this won't work. 
Usually the best approach is to copy the items you want to keep:

_list = [item for item in _list if keep(item)]

If the list is huge you can also delete in reverse order:

for i in reversed(len(_list)):
    if discard(_list[i]):
        del _list[i]

(If you want to delete /all/ items use _list.clear() or del _list[:])




More information about the Python-list mailing list