Reputation: 1529
So I've got into trouble when I want to delete a sequence of index from a list
for i in linked_node:
del l[i]
the linked_node is the index sequence this code simply wont work cause del changed the size of the list
using a for loop , I can do this by appending them to a new list
l1 = []
for i in range(len(l)):
if i is not in linked_node:
l1.append(l[])
my question is , how to do this in an elegent way?without creating another list
Upvotes: 1
Views: 1051
Reputation: 60024
Use a list comprehension instead:
>>> l = ['hi', 'hello', 'hey', 'hai']
>>> indexes = {1, 2}
>>> [j for i, j in enumerate(l) if i not in indexes]
['hi', 'hai']
Upvotes: 5
Reputation: 16029
Also using the reversed iteration trick, but somewhat faster because you don't have to sort your list:
l = ["a", "b", "c", "d"]
for idx in range(len(l)-1, -1, -1):
i = l[idx]
print(i)
if i in ["b", "d", "c"]:
del(l[idx])
print(l)
>>> d
>>> c
>>> b
>>> a
>>> ['a']
Upvotes: 0
Reputation: 11968
you can do something like:
linked_node.sort(reversed=True)
for i in linked_node:
del l[i]
Now this should work because the indices you are interested in stay the same. Another way to do it, if it's already sorted:
for (x, i) in enumerate(linked_node):
del l[i - x]
Upvotes: 1
Reputation: 82949
If you do not want to create a new list, as in @Haidro's solution, but really delete the elements at the given indices from the existing list, you could also reverse the list of indices, so that indices at the end of the list are deleted first.
for i in sorted(linked_node, reverse=True):
del l[i]
Otherwise, the elements you want to delete will shift to the left as you delete elements, thus changing their indices, and you end up deleting the wrong elements, or getting an IndexError
.
Upvotes: 2