1

I've been getting back into python after a few years away and wanted to write a simple script that printed out all prime numbers between 1 and n.

I did complete it but one code change I had to make is confusing me. When I loop through a range 1:n I get the correct output. However when I loop through a list(range(1:n)) it breaks. Not sure if I'm missing something stupid...

The working version of the code is as follows

#Choose max number to check
n = 100

#Initialize list of all potential primes 
primes = list(range(1,n))

#Loop through each potential prime
for i in range(1,n):
    j = 2
    #Divide each potential by every number below it from 2 up to i - 1, if the modulus is 0, then number is divisible, so remove from list of potential primes.
    while j < i:
        if i % j == 0:
            if i in primes: primes.remove(i)
            break
        j += 1
print(primes)

In the primary loop, we loop through i in range(1,n). However, if instead try to loop through the list primes, as in the below code example, it weirdly returns 9, 39, 69, 99 and other numbers ending in 9 as being prime.

#Choose max number to check
n = 100

#Initialize list of all potential primes 
primes = list(range(1,n))

#Loop through each number in full list
for i in primes:
    j = 2
    #Divide each potential prime by every number below it from 2 up to i - 1, if the modulus is 0, then number is divisible, so remove from list of potential primes.
    while j < i:
        if i % j == 0:
            if i in primes: primes.remove(i)
            break
        j += 1
print(primes)

Any other comments about improvements (performance or otherwise) are welcome - as I said I'm just trying to dive back in with some simple things.

Nilly
  • 93
  • 6
  • 5
    Don't remove list items while iterating over it – RomanPerekhrest Dec 26 '19 at 18:31
  • 2
    It comes down to the fact that you are iterating over a collection (`primes`) while also modifying it, by removing elements. This is never a good idea, and in this case it results in you stepping over some iterations. – Paul M. Dec 26 '19 at 18:32

1 Answers1

1

Both programs change primes as they progress; the second program uses primes to control the loop, while the first does not.

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101