delete items from list by indices

blumenkraft vohsrea at gmail.com
Wed Sep 23 05:30:36 EDT 2009


On 23 сен, 12:48, Peter Otten <__pete... at web.de> wrote:
> blumenkraft wrote:
> > 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?
>
> Why's that obsession with speed?
>
> >>> items = ["a", "b", "c", "d"]
> >>> delenda = [0, 3]
> >>> for i in sorted(delenda, reverse=True):
>
> ...     del items[i]
> ...>>> items
>
> ['b', 'c']
>
> >>> items = ["a", "b", "c", "d"]
> >>> delenda = set([0, 3])
> >>> items = [item for index, item in enumerate(items) if index not in
> delenda]
> >>> items
>
> ['b', 'c']
>
> If you really need to modify the list in place change
>
> items = [item for ...]
>
> to
>
> items[:] = [item for ...]
>
> Try these and come back to complain if any of the above slows down your
> script significantly...
>
> Peter

Thanks, it helped (I didn't know about keyword argument "reverse" in
sorted function)



More information about the Python-list mailing list