-3

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?

Example

vince
  • 27
  • 5
  • 2
    No because you did not share your code. – rdas May 09 '20 at 20:41
  • 4
    Only ***text*** is acceptable in questions. Not pictures of code – rdas May 09 '20 at 20:42
  • In the line before the error occurs print `x` and `len(listitems) + 1` and see what happens. – Matthias May 09 '20 at 20:53
  • 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) – Matthias May 09 '20 at 20:56
  • This might be a better target for the duplicate https://stackoverflow.com/questions/6260089/strange-result-when-removing-item-from-a-list – Matthias May 09 '20 at 20:57

2 Answers2

0

[x for x in listitems if x != 1 and x!= 4]

Tomer Shinar
  • 415
  • 3
  • 13
  • While it’s acceptable to provide code-only answers, it’s often more useful for the community if you can also provide an explanation of the code and help people understand _why_ it addresses the problem. That can reduce the number of follow-up questions, and help new developers understand the underlying concepts. Would you mind updating your question with additional detail? – Jeremy Caney May 10 '20 at 00:33
-2

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]
CharlieG
  • 38
  • 10