0

I am using the code to find prime factors, but the for loop never picks up 65. why?

import math
sq = int(math.sqrt(13195))
lis = []
for x in range(2,sq):
    if 13195 % x == 0:
        lis.append(x)      
for y in lis:
    print(y)
    for z in range(2,y):
        if y % z == 0:
            print(y,"is not a prime")
            if y in lis:
                lis.remove(y)
            else:
                continue
print(lis)

I expect the output to be [5,7,13,29] but the actual output is [5,7,13,29,65]

rdas
  • 20,604
  • 6
  • 33
  • 46

1 Answers1

2

You are removing elements while iterating over the same list, use a slice or a copy for solving it:

for y in lis[::]: # make a copy of the original list to avoid the problem
    print(y)
    for z in range(2,y):
        if y % z == 0:
            print(y,"is not a prime")
            if y in lis:
                lis.remove(y)
            else:
                continue
Netwave
  • 40,134
  • 6
  • 50
  • 93