Removing items from a list simultaneously

R

Ross

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].
 
S

Steven D'Aprano

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]
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,982
Messages
2,570,190
Members
46,740
Latest member
AdolphBig6

Latest Threads

Top