pythonlistremove-if

Remove elements within a list of indexes in python


I have a list of values:

list_of_value = [1,3,4,2,3,"start",3,4,5,"stop",5,6,7,6,"start",5,6,7,"stop"]

I need to remove from the list the elements between "start" and "stop" (boundaries included).

The output should be something like:

[1,3,4,2,3,5,6,7,6]

I tried something like this:

for i, el in enumerate(list_of_values):
    if "start" in el:
        start_index = i
    if "stop" in el:
        stop_index = i
        for a in range(start_index,stop_index):
            del list_of_values[a]

but it's not working.

Can you help me?

Thanks, Davide


Solution

  • My solution is that you have a variable called flag to know when to append values to your output. It will only append after stop and not between start and stop

    output = []
    flag = False
    for el in list_of_values:
        if "start" == el and not flag:
            flag = True
        if "stop" == el:
            flag = False
            continue
        if not flag:
            output.append(el)