1

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

5
  • Are you looping over the list itself or not? Because your code says one thing, but your error description says another. Commented Sep 7, 2013 at 10:05
  • Either you are looping over l and are deleting while looping over it (which won't work without creating a copy) or you are looping over a list of indices. Commented Sep 7, 2013 at 10:05
  • You'll need to show us more code for us to give you any meaningful help here. Commented Sep 7, 2013 at 10:05
  • thanks, I edited it to make it more specific Commented Sep 7, 2013 at 10:08
  • btw. 'del l[i]' will fail because you don't put in the index of you listitem, but the item itself. Commented Sep 7, 2013 at 10:21

4 Answers 4

5

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']
Sign up to request clarification or add additional context in comments.

2 Comments

indexes = set([1, 2])
@hughdbrown Changed :)
2

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.

1 Comment

yeah, haidro's solution also creat a new list, but in a more elegent way
1

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]

Comments

0

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']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.