Deleting more than one element from a list

Raymond Hettinger python at rcn.com
Sun Apr 25 09:17:06 CEST 2010


On Apr 21, 12:56 pm, candide <cand... at free.invalid> wrote:
> Is the del instruction able to remove _at the same_ time more than one
> element from a list ?
>
> For instance, this seems to be correct :
>
>  >>> z=[45,12,96,33,66,'ccccc',20,99]
>  >>> del z[2], z[6],z[0]
>  >>> z
> [12, 33, 66, 'ccccc', 20]
>  >>>
>
> However, the following doesn't work :
>
>  >> z=[45,12,96,33,66,'ccccc',20,99]
>  >>> del z[2], z[3],z[6]
> Traceback (most recent call last):
>    File "<stdin>", line 1, in <module>
> IndexError: list assignment index out of range
>  >>>
>
> Does it mean the instruction
>
> del z[2], z[3],z[6]
>
> to be equivalent to the successive calls
>
> del z[2]
> del z[3]
> del z[6]
>
> ?

Looks like you got a lot of good answers to the question as asked.

FWIW, successive delete operations on a list are dog slow.
It is better to delete all of the entries in one pass.
There are several ways to do it.  Here's one:

>>> z=[45,12,96,33,66,'ccccc',20,99]
>>> targets = [2, 3, 6]
>>> PLACEHOLDER = object()
>>> for i in targets:
...	z[i] = PLACEHOLDER
>>> z[:] = [elem for elem in z if elem is not PLACEHOLDER]

Here's another:

>>> z=[45,12,96,33,66,'ccccc',20,99]
>>> targets = set([2, 3, 6])
>>> z[:] = [elem for i, elem in enumerate(z) if i not in targets]

Besides being scaleable, these two examples have some nice learning
points.  Hopefully, you will find them useful.


Raymond



More information about the Python-list mailing list