How to Find Prime Number in Python – Examples and Explanation

Chart of prime numbersTo find a prime number in Python, we can have to create a special function solely for this purpose. There is no built-in function in Python for this purpose. By definition, a prime number is a natural integer number which is greater than 1 and has no positive divisors other than 1 and itself. In other words an integer number only divisible by 1 and itself.

Prime numbers start from 2 and their sequence is 2, 3, 5, 7, 11, 13, 17, 23… and up to the infinity. As of January 2016, the largest known prime number has 22,338,618 decimal digits. For further reading, you can follow this Wikipedia article about Prime Numbers.

There are various ways to find whether a number is a prime or not in Python programming language. Here is some better code snippet for this purpose.


Find a Prime Number in Python using Function


23 is a prime number

Find Prime Number using Regular Express in Python Language


21 is not a prime number


Find Prime Numbers in Range using List Comprehension in Python


Prime numbers between 2 and 20
[2, 3, 5, 7, 11, 13, 17, 19]


Find Prime Numbers in Range using Generator in Python

Note: range in Python 3.x is xrange in Python 2.x. Python 2 range is removed in Python 3. Now in Python 3 range is behaves like a generator. It is much faster and uses less memory.


Prime numbers between 2 to 20


A good discussion on Prime Numbers in Python can also be found here.