0

I'm new to python and I'm trying to code a simple program, I've seen others' questions about the same error, however I'm not getting to apply any solution to my code.

for vh in range(len(self.parked_vehicles)):
            if self.parked_vehicles[vh] == vehicle:
                del(self.parked_vehicles[vh])
                self.places += vehicle.size
                self.parked = False
                print('Vehicle unparked!')

When I try to test this code above with unittest I have this output:

    if self.parked_vehicles[vh] == vehicle:
IndexError: list index out of range

What can I do in this situation? I'm not getting to solve it at all. Thanks.

JoaoP_L
  • 29
  • 5
  • You are adjusting self.parked_vehicles while looping it. Make a copy first then adjust that copy so your loop stays working. You can use .copy() for this. – Wimanicesir Mar 06 '20 at 13:54
  • The cause is deleting list elements while iterating over it, which is usually a bad idea. – Jussi Nurminen Mar 06 '20 at 13:56
  • in addition, even without deleting element you will get same error at the end, because indexes are 0-based and you the max index is len-1. Iterating like this is not pythonic – buran Mar 06 '20 at 14:00
  • 1
    This answers your question: [Why does del list\[0\] in a for-loop only delete half the list?](https://stackoverflow.com/questions/45683615/why-does-del-list0-in-a-for-loop-only-delete-half-the-list) – Jongware Mar 06 '20 at 14:06
  • 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) – Wimanicesir Mar 08 '20 at 10:21

0 Answers0