I am using a function to remove list items if they are equal to 1 or '4'. When I run the code, I get an error "IndexError: list index out of range"
Can you tell me why this is happening and how I could fix?
I am using a function to remove list items if they are equal to 1 or '4'. When I run the code, I get an error "IndexError: list index out of range"
Can you tell me why this is happening and how I could fix?
[x for x in listitems if x != 1 and x!= 4]
There are 2 reasons this is happening. The first is that you have iterated len(listitems)+1 times, this would iterate 5 times with a list of length 4, which would cause the error.
Secondly, as you call the .pop() function, the list gets shorter, so when you call the 4th element, the list is now only 3 long, causing the error.
A better way to do what you want is with list comprehensions, as shown by Tomer Shinar, however if you want to keep your code in the same style, keep a count of the number of items removed, and adjust your index accordingly.
def func(listitems):
numRemoved = 0
for x in range(len(listitems)):
index = x-numRemoved
if listitems[index] == 1 or listitems[index] == '4':
listitems.pop(index)
numRemoved += 1
return listitems
testlist = [1,2,3,'4']
print(testlist) # [1, 2, 3, '4']
func(testlist)
print(testlist) # [2, 3]