Fwd: PYTHON BUG. deleting elements of list.

Richard Damon Richard at Damon-Family.org
Tue Sep 8 19:18:57 EDT 2020


On 9/8/20 7:06 PM, 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]
>
The issue isn't so much that he is modifying the list that he is
iterating over, but also when he deletes _list[0], all the other
elements move down, so the next time when he does a del _list[1], that
will delete what started as _list[2], and with your code, when he gets
half way done he will hit an index error as he tries to delete _list[26]
from a list with only 25 elements.

-- 
Richard Damon



More information about the Python-list mailing list