How to Find Prime Numbers in Range in Python

Prime numbers are important in mathematics and computer science and are often used in cryptography and other applications that require unique keys or factors.

What is Prime Number?

A prime number is a positive integer greater than 1 that is only divisible by 1 and itself.

How to Find Prime Number in Python

To find prime numbers in Python, use the for loop to iterate over the range and check if each number is prime.

def is_prime(n: int) -> bool:
  # Check if n is less than 2, which is not prime
  if n < 2:
    return False

  # Check if n is divisible by any number from 2 to n-1
  for i in range(2, n):
    if n % i == 0:
      return False

  # If the loop completes without finding a divisor, n is prime
  return True

print(is_prime(5))

Output

True

In this example, we are checking for the number 5, a prime number, and the program verifies that by returning True.

Let’s check for the number 4 and see if it is a prime number.

def is_prime(n: int) -> bool:
  # Check if n is less than 2, which is not prime
  if n < 2:
    return False

  # Check if n is divisible by any number from 2 to n-1
  for i in range(2, n):
    if n % i == 0:
      return False

  # If the loop completes without finding a divisor, n is prime
  return True

print(is_prime(4))

Output

False

You can then use the is_prime() function to find the prime numbers.

Python find prime numbers in range

To find prime numbers in the range in Python, use list comprehension. The list comprehension will create a new list filled with prime numbers based on the existing list.

We will check every element in the range or this case, the existing list and see if it is a prime number or not by passing each value to the is_prime() function.

If the number between the range is prime, it will be added to the new list, and after iterating the range, we will have the final list of prime numbers.

We will create a find_primes_in_range() function to find all prime numbers between 1 and 50.

def is_prime(n: int) -> bool:
  # Check if n is less than 2, which is not prime
  if n < 2:
    return False

  # Check if n is divisible by any number from 2 to n-1
  for i in range(2, n):
    if n % i == 0:
      return False

  # If the loop completes without finding a divisor, n is prime
  return True

def find_primes_in_range(start: int, end: int) -> list[int]:
  # Use a list comprehension to find all prime numbers in the range
  return [n for n in range(start, end + 1) if is_prime(n)]

prime_numbers = find_primes_in_range(1, 50)
print(prime_numbers)

Output

[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]

Here is the list of all the prime numbers from the range of 1 to 50 in Python.

Conclusion

The best way to find the prime number for a given range is to write a custom function that checks if that number is prime or not and then use the list comprehension technique to find the prime numbers from the given range.

That’s it.

Leave a Comment