Home > Net >  Finding all the prime numbers in a list in Python
Finding all the prime numbers in a list in Python

Time:11-25

I want to loop through a list and find all the numbers that are prime

arr = [1,2,3]

for i in range(len(arr)):
 if arr[i] > 1:
        for j in range(2, int(arr[i]/2) 1):
            if (arr[i] % j) == 0:
                print(arr[i], "is not prime")
            else:
                print(arr[i], "is prime")
  else:
        print(arr[i], "is not prime")

This only prints out "1 is not prime." I am guessing it has something to do with the range(len()) of the for loop.

CodePudding user response:

arr = list(range(20))

def is_prime(n):
    if n < 2:
        return False
    for i in range(2, int(n**0.5) 1):
        if n % i == 0:
            return False
    return True

def find_primes(array):
    return list(filter(is_prime, array))

print(find_primes(arr))

returns: [2, 3, 5, 7, 11, 13, 17, 19]

CodePudding user response:

The problem with your code is as follows

int(arr[i]/2) 1) is smaller than 2, thenceforth range(2, int(arr[i]/2) 1)) has no elements. The for loop doesn't execute for 2 and 3. These two cases need to be treated apart.

The second problem is that for greater numbers, you're deciding for every iteration in the innerloop whether the number is prime or not.

Here is a slight modification of your code that should work:

arr = range(20)

for i in range(len(arr)):
    if arr[i] > 3:
        is_prime = True
        for j in range(2, int(arr[i]/2) 1):
            if (arr[i] % j) == 0:
                is_prime = False
                break
            else:
                continue
        print(arr[i], "is prime" if is_prime else "is not prime")
    elif arr[i] in [2,3]:
        print(arr[i], "is prime")
    else:
        print(arr[i], "is not prime")
  • Related