Search code examples
pythonloopsindexoutofboundsexception

index out of bound while looping through a list and deleting some of the elements in python


I'm trying to loop through a list of numbers from 2 to 10000 and delete the mutliples of 2,3,4, and to 100 but not these numbers but everytime i delete an item the length of the list shrinks so it produces an index out of bound error how do i fix it?

enter image description here


Solution

  • Here is an example that might work for you. It leverages list comprehension. I didn't quite understand your code, especially the index increment in the while loop that only runs until multiple is 101.

    def is_multiple(number):
        for m in range(2, 101):
            if number is not m and number % m == 0:
                return True
    
    
    numbers = range(2, 10000)
    
    numbers = [n for n in numbers if not is_multiple(n)]
    
    print(numbers)