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.