Deleting more than one element from a list

Mensanator mensanator at aol.com
Wed Apr 21 16:49:55 EDT 2010


On Apr 21, 2: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]

That's part of the problem. Let's look at a better example.

>>> z = [0,1,2,3,4,5,6]
>>> del z[0],z[3],z[6]
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    del z[0],z[3],z[6]
IndexError: list assignment index out of range
>>> z
[1, 2, 3, 5, 6]

Yes, the error was caused by the list shrinking between calls,
so the 6 did not get deleted. But notice that 3 is still there
and 4 is missing.

If you must delete this way, do it bottom up so that the index
remains valid for the subsequent calls:

>>> z = [0,1,2,3,4,5,6]
>>> del z[6],z[3],z[0]
>>> z
[1, 2, 4, 5]


>
> ?




More information about the Python-list mailing list