0

I have a list of numbers [7, 9, 11, 13, 15, 20, 23] and I need to create a list of Prime numbers from given list.

I have written below code but this results 9 & 15 as prime too. I am not getting what I am missing here.

a = [7, 9, 11, 13, 15, 20, 23] 

x = []
for i in range (0, len(a)):
    num = a[i]
    for m in range (2,num):
        if (num % m)==0:
            break
        else:
            print('This is prime', num)
            x.insert(i, num)
            break

I Expect the output list x as [7, 11, 13, 23].

DjaouadNM
  • 22,013
  • 4
  • 33
  • 55
Rohit
  • 97
  • 1
  • 2
  • 9
  • This question (with [my answer](https://stackoverflow.com/a/53451147/9225671)) has a few ways on how to calculate prime numbers in Python. – Ralf Sep 02 '19 at 19:10

1 Answers1

5

If num % m != 0 doesn't mean that num is prime, it must be true for all possible m values (which can be reduced by going up to num // 2, and can even be reduced to go up to just sqrt(num)), for that, you can use a for ... else block (the else block will execute only when the for exits normally, without a break, which only happens with prime numbers):

a = [7, 9, 11, 13, 15, 20, 23] 

x = []
for num in a:   #   iterate with the value when you don't need the index
    for m in range(2, (num // 2) + 1):
        if num % m == 0:
            break
    else:
        print('This is prime', num)
        x.append(num)   #   use `append` to insert at the tail of the list

print(x)

Output:

This is prime 7
This is prime 11
This is prime 13
This is prime 23
[7, 11, 13, 23]
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55