Search code examples
pythonarrayslistdel

Del list and next list element in list if string exist


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.


Solution

  • 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