wanted to have a single list instead of multiple list showing prime numbers

Question:

I tried to make a program that shows all prime number till the limit
but the code shows each factor adding to the ans list.
How do I fix this?

limit = 34
num = [value for value in range(2, limit + 1)]
factor = 2
ans = []
while True:
    if factor not in num:
        factor += 1
    elif factor in num:
        ans.append(factor)
        for ele in num:
            if ele % factor == 0:
                num.remove(ele)
        print(ans)

Expected Output

[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]
Asked By: Broil

||

Answers:

You need to ensure the factor variable is bounded.

limit = 34
num = list(range(2, limit + 1))
factor = 2
ans = []
while factor <= limit+1:
    if factor not in num:
        factor += 1
    elif factor in num:
        ans.append(factor)
        for ele in num:
            if ele % factor == 0:
                num.remove(ele)
print(ans)
Answered By: bn_ln
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.