-1

I have an example:

list = [['2 a', 'nnn', 'xxxx','last'], ['next, next'], ['3', '4', 'next']]

for i in range(len(list)):
  if list[i][-1] == "last":
    del(list[i+1])
    del(list[i])

I'd like to delete this list where the last item is "last" and the next item on the list. In this example there is a problem every time - I tried different configurations, replacing with numpy array - nothing helps.

Trackback: IndexError: list index out of range

I want the final result of this list to be ['3', '4', 'next']

Give me some tips or help how I can solve it.

DeepSea
  • 305
  • 2
  • 15
  • When you [Catch the error](https://docs.python.org/3/tutorial/errors.html#handling-exceptions) and inspect/print relevant data in the except suite - what is the value of `i`? If you delete items from the list will the *original* `range(len(list))` still apply? – wwii May 12 '20 at 18:26
  • Does this answer your question? [How to remove items from a list while iterating?](https://stackoverflow.com/questions/1207406/how-to-remove-items-from-a-list-while-iterating) – wwii May 12 '20 at 18:28
  • 1
    Instead of deleting the list, try creating a new list and copy elements from the old list. This will, of course, depend on your resource constraints. – Palash Goel May 12 '20 at 18:34
  • @wwii I've also checked it and it works for ints – DeepSea May 12 '20 at 18:35
  • @PalashGoel I tried it too, but the only solution I had was `list2.append(list[i])` - with the condition `if list[i][-1] ! = "last"` - but I need to delete both `list[i]` and as well as `list[i+1]` – DeepSea May 12 '20 at 18:45

2 Answers2

0

Try this:

l = [['2 a', 'nnn', 'xxxx','last'], ['next, next'], ['3', '4', 'next']]
delete_next = False
to_ret = []
for x in l:
    if x[-1] == 'last':
        delete_next = True
    elif delete_next:
        delete_next = False
    else:
        to_ret.append(x)

Using a variable to store if this needs to be deleted

Palash Goel
  • 624
  • 6
  • 17
  • yes, but in this case it breaks my previous list - if the list is, for example:`l = [['2 a', 'nnn', 'xxxx','last'], ['next, next'], ['3', '4', 'next'],["text","text"]]` the effect of this code will be: `['3', '4', 'next', 'wwa', 'wwaa']` but I want the structure to be preserved: `['3', '4', 'next'],["text","text"]` – DeepSea May 12 '20 at 19:39
  • No. The output will be as expected – Palash Goel May 12 '20 at 19:43
  • 1
    `to_ret.append(x)` - this will work fine. The `+ =` operator will add to one list. Anyway, thank you, all you had to do was use bool and solve the problem - I don't know why I didn't think of it before. – DeepSea May 12 '20 at 19:50
  • Didn't know there was a difference b/w += and .append. Thanks! – Palash Goel May 13 '20 at 04:52
0

Loop over the list, if the last element of that iteration == 'last' then skip, else, append to a new list.

Also, it is not recommended to edit lists while iterating over them as strange things can happen, as mentioned in the comments above, like the indexes changing.

l = [['2 a', 'nnn', 'xxxx','last'], ['next, next'], ['3', '4', 'next']]
newlist = []
for i in l:
    if i[-1] == 'last':
        continue
    else:
        newlist.append(i)
matman9
  • 390
  • 3
  • 17
  • would also rename your list to something else, like L, as list is an object type in python – matman9 May 12 '20 at 18:59
  • While it’s acceptable to provide code-only answers, it’s often more useful for the community if you can also provide an explanation of the code and help people understand _why_ it addresses the problem. That can reduce the number of follow-up questions, and help new developers understand the underlying concepts. Would you mind updating your question with additional detail? – Jeremy Caney May 12 '20 at 23:50