delete items from list by indices

Ishwor ishwor.gurung at gmail.com
Wed Sep 23 11:19:01 CEST 2009


Hi

2009/9/23 blumenkraft <vohsrea at gmail.com>:
> Hi,
>
> I have some list:
> x = [8, 9, 1, 7]
> and list of indices I want to delete from x:
> indices_to_delete = [0, 3], so after deletion x must be equal to [9,
> 1].
>
> What is the fastest way to do this? Is there any builtin?

Try this-
>>> x = [8, 9, 1, 7]
>>> [x.pop(i) for i in sorted(indices_to_delete,reverse=True)]
[7, 8]
>>> x
[9, 1]

Built-in used here is `sorted' and method on list used here is `pop'.
With regards to efficiency you may want to use the methods of list
which is more intuitive afaik and useful as its more reflective of
effect on the type list. It's a trivial choice here but later it might
help.
-- 
Regards,
Ishwor Gurung



More information about the Python-list mailing list