-1

I'm trying to do a function which deletes the negative numbers from a list that given externally and returns the new list. But my code gives me "IndexError: list index out of range" error. How can I fix it?

class Prtc:
def __init__(self, x, _lst):
    self.x = x
    self._lst = _lst
    
def del_neg(self, _lst):
    i = 0
    while i < len(_lst):
        if _lst[i] < 0:
            _lst.remove(i)
        i += 1
    return _lst
animoxl
  • 15
  • 4
  • Please indent properly and include code that demonstrates the behavior you claim. – Manuel Apr 16 '21 at 18:17
  • 3
    Does this answer your question? [How to modify list entries during for loop?](https://stackoverflow.com/questions/4081217/how-to-modify-list-entries-during-for-loop) – AcK Apr 16 '21 at 18:22
  • @ack That's not about deleting elements. – Manuel Apr 16 '21 at 18:23

2 Answers2

1

The problem is everytime you remove i you actually shorten the list here is a quick fix:

class Prtc:
    def __init__(self, x, _lst):
        self.x = x
        self._lst = _lst
        
    def del_neg(self, _lst):
        i = 0
        while i < len(_lst):
            if _lst[i] < 0:
                _lst.remove(_lst[i])
                i -= 1
            i += 1
        return _lst

That said, there are much more efficient ways of doing this:

def del_neg(self, _lst):
    return [item for item in _lst if item >= 0]
LPR
  • 400
  • 1
  • 8
0

As LPR said the problem is that you shorten the list every time you delete an item. The usual way that one can do this without playing with indices too much is going in reverse:

class Prtc:
def __init__(self, x, _lst):
    self.x = x
    self._lst = _lst
    
def del_neg(self, _lst):
    i = len(_lst) - 1
    while i >= 0:
        if _lst[i] < 0:
            _lst.remove(i)
        i -= 1
    return _lst

Although if you don't need to do it manually you should go with his second code, that being the most pythonic way of doing it

Andres de Lago
  • 111
  • 1
  • 9