0

I am trying to remove all items that have a due date equal to the current day, however, when I use this code because I am removing items from the list it changes the length and then I get the error list index out of range. How do I fix this?

 for i in range(len(self.__items)):
     if(self.__items[i]['duedate']==self.__currentDay):
         self.__items.remove(self.__items[i])
         self.__numItems-=1
Sam
  • 9
  • 2
  • `self.__items = [i for i in self.__items if i['duedate']!=self.__currentDay]`. Get rid of `self.__numItems` and just use `len(self.__items)`. – Samwise Mar 19 '21 at 01:41
  • 1
    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) – Nick Mar 19 '21 at 01:41

1 Answers1

1

You have to iterate backward when you are changing the length of the list during iteration:

for i in range(len(self.__items)-1, -1, -1):
    if (self.__items[i]['duedate'] == self.__currentDay):
        self.__items.remove(self.__items[i])
        self.__numItems -= 1
pakpe
  • 5,391
  • 2
  • 8
  • 23