1

I am new to Python, so apologies if this seems silly. But, I'm trying to remove certain indices from a list with a for loop and the range function, but rather than the range being incremented by one, it's going up by 2, even though I didn't pass any additional argument.

Here is what I tried:

def remove_middle(lst,start,end):
  for i in range(start,(end+1)) :
    lst.pop(i)
  return lst

print(remove_middle([4, 8, 15, 16, 23, 42], 1, 3))

I was expecting [4, 23, 42]
but received [4, 15, 23]

Talha Tayyab
  • 8,111
  • 25
  • 27
  • 44
gix
  • 37
  • 4
  • 4
    You don't want to modify the list while iterating over it. Instead create a new list with a list comprehension. – Allan Wind Jan 08 '23 at 01:46
  • You should start by debugging or simply `print(i)` during the loop. It is not incremented by 2, the problem is that you modified the underlying list, so the indices of the elements shift. – Plagon Jan 08 '23 at 01:48
  • Food for thought: [How to remove items from a list while iterating?](https://stackoverflow.com/questions/1207406/how-to-remove-items-from-a-list-while-iterating) – wwii Jan 08 '23 at 02:31
  • On the first iteration it pops `8` and `lst` becomes `[4,15,16,23,42]`. On the next iteration *`i=2`* and `lst.pop(i)` removes `16` ... – wwii Jan 08 '23 at 02:35
  • 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) – wovano Jan 12 '23 at 06:08

2 Answers2

2

Here is an implementation that uses a list comprehension:

def remove_middle(lst, start, end):
    return [lst[i] for i in range(len(lst)) if i < start or i > end]

You can also combine two slices:

def remove_middle(lst, start, end):
    return lst[:start] + lst[end+1:]
Allan Wind
  • 23,068
  • 5
  • 28
  • 38
1

You should not remove elements from a list while iterating rather you can:

def remove_middle(lst,start,end):
    k=[]
    for x,y in enumerate(lst):
        if x<start or x>end:
            k.append(y)
    return k 

print(remove_middle([4, 8, 15, 16, 23, 42],1,3))
#output [4, 23, 42]
Talha Tayyab
  • 8,111
  • 25
  • 27
  • 44