Reputation: 21
list1 = [1,2,5,6,7,8,10,41,69,78,83,100,105,171]
index_list = [0,4,7,9,10]
how do I pop an item from list1 using indexes from index_list?
output_list = [2,5,6,8,10,69,100,105,17]
Upvotes: 1
Views: 5088
Reputation: 2047
list1 = [1,2,5,6,7,8,10,41,69,78,83,100,105,171]
index_list = [0,4,7,9,10]
print([ t[1] for t in enumerate(list1) if t[0] not in index_list])
RESULT
[2, 5, 6, 8, 10, 69, 100, 105, 171]
enumerate will create a structure like below.
[(0, 1), (1, 2),(2, 5),(3, 6),(4, 7),(5, 8),...(13, 171)]
Where t = (0,1) (index,item)
t[0] = index
t[1] = item
Upvotes: 1
Reputation: 10789
Use list.remove(item)
for n in reversed(index_list):
list1.remove(list1[n])
or list.pop(index)
for n in reversed(index_list):
list1.pop(n)
Both methods are described here https://docs.python.org/2/tutorial/datastructures.html
Use reversed() on your index_list (assuming that the indices are always ordered like in the case you have shown), so you remove items from the end of the list and it should work fine.
Upvotes: 1
Reputation: 3226
You could try this -
for index in sorted(index_list, reverse=True):
list1.pop(index)
print (list1)
pop()
has an optional argument index. It will remove the element in index
Upvotes: 0
Reputation: 82899
How about the opposite: Retain those elements that are not in the list:
>>> list1 = [1,2,5,6,7,8,10,41,69,78,83,100,105,171]
>>> index_list = [0,4,7,9,10]
>>> index_set = set(index_list) # optional but faster
>>> [x for i, x in enumerate(list1) if i not in index_set]
[2, 5, 6, 8, 10, 69, 100, 105, 171]
Note: This does not modify the existing list but creates a new one.
Upvotes: 1