What is the sympy.primerange() method in Python?

What is the sympy library?

sympy is a library used for symbolic mathematics.

pip can be used to install sympy. You can refer to the following command to do this.

pip install sympy

The primerange method

The primerange method is used to get the prime numbers occurring in the given range. While the starting number is included in the range, the ending number is excluded from the range, that is, [starting_number, ending_number).

If the ending_number is not given or is None, this method returns all the prime numbers less than the starting_number. If either starting_number or ending_number is negative, this method returns an empty list.

Syntax

sympy.primerange(a, b=None)

Parameters

  • a: The starting number of the range.
  • b: The ending number of the range.

Return value

The method returns all the prime numbers in the range [a, b].

Code

import sympy
a = 10
print("sympy.primerange(%s) = %s" % (a, list(sympy.primerange(a))))
b = 20
print("sympy.primerange(%s, %s) = %s" % (a, b, list(sympy.primerange(a, b))))

Code explanation

  • Line 1: We import the sympy package.
  • Line 3: We define the starting number of the range as a.
  • Line 5: We print the output of the primerange() method when only the starting_number is given. The output consists of all the prime numbers less than a.
  • Line 7: We define the ending number of the range, that is, b.
  • Line 9: We print the output of the primerange() method when the starting and ending numbers are given. The output consists of all the prime numbers in the range [a, b].

Free Resources