Fwd: PYTHON BUG. deleting elements of list.

Chris Angelico rosuav at gmail.com
Wed Sep 9 03:51:40 EDT 2020


On Wed, Sep 9, 2020 at 5:45 PM Peter Otten <__peter__ at web.de> wrote:
>
> Peter Otten wrote:
>
> > If the list is huge you can also delete in reverse order:
> >
> > for i in reversed(len(_list)):
>
> Make that reversed(range(len(_list))).
>
> >     if discard(_list[i]):
> >         del _list[i]
>
> Example:
>
> >>> items = ['a', 'b', 'c', 'd', 'e']
> >>> for i, item in enumerate(items):
> ...     if item in "bcd":
> ...         del items[i]
> ...
> >>> items
> ['a', 'c', 'e']
> >>> items = ['a', 'b', 'c', 'd', 'e']
> >>> for i in reversed(range(len(items))):
> ...     if items[i] in "bcd":
> ...         del items[i]
> ...
> >>> items
> ['a', 'e']
>

But that's still pretty clunky AND inefficient (deleting from the
middle of a list is a slow operation). Filtering is far better.

items = [i for i in items if i not in "bcd"]

And if you absolutely have to mutate in place:

items[:] = [i for i in items if i not in "bcd"]

ChrisA


More information about the Python-list mailing list