Deleting more than one element from a list

Gary Herron gherron at digipen.edu
Wed Apr 21 22:40:50 CEST 2010


candide 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]

Yes, those are equivalent.  The reason it fails is that, by the time it 
gets around to the third delete, there is no longer in index [6] in the 
list.  The element you were thinking of is now at index [4].

This, however, will work as you expected:

    del z[6], z[3],z[2]




-- 
Gary Herron, PhD.
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418




More information about the Python-list mailing list