Unexpected outcome with the range function, slightly confused

Question:

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]

Asked By: gix

||

Answers:

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:]
Answered By: Allan Wind

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]
Answered By: God Is One