Removing items from a list simultaneously

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Tue Apr 21 05:18:35 CEST 2009


On Mon, 20 Apr 2009 20:09:12 -0700, Ross wrote:

> Is there a quick way to simultaneously pop multiple items from a list?
> For instance if i had the list a = [1,2,3,4,5,6,7] and I wanted to
> return every odd index into a new list, my output would be new_list =
> [2,4,6] or similarly if I wanted to return each index that was one away
> from the midpoint in a, I would get [3,5].

Do you really need to remove them? Removing items from a list tends to be 
slow. The more Pythonic approach is to create a new list:


>>> a = [1,2,3,4,5,6,7]
>>> b = a[1::2]  # odd items
>>> midpoint = len(a)//2
>>> c = [a[midpoint - 1], a[midpoint+1]]
>>>
>>> b
[2, 4, 6]
>>> c
[3, 5]


If you really do need to delete items from a list, you can do this:


>>> del a[0]  # delete the item at position 0
>>> a
[2, 3, 4, 5, 6, 7]
>>> a.remove(2)  # delete the first item equal to 2
>>> a
[3, 4, 5, 6, 7]


-- 
Steven



More information about the Python-list mailing list