How to use the random.randrange() method in Python

Overview

The random.randrange() method returns a randomly selected element from a given range. This method is similar to random.choice(), except random.randrange() does not build a range object.

Syntax

random.randrange(start,stop,step)

Parameters

  • start (optional): An integer that specifies the position where the elements to be returned should start from.
  • stop (optional): An integer that specifies the position where the elements to be returned should end.
  • step (optional): An integer that specifies the increment in step size.

Example code

Let’s use the random.randrange() method to return elements for a given range.

import random
# using the stop parameter
print(random.randrange(2))
# using both the start and stop parameters
print(random.randrange(2,15))
# using the start, stop and step parameters
print(random.randrange(2,15,3))

Code explanation

  • Line 1: We import the random module.
  • Line 4: We use the random.randrange() method to return an integer, starting from 0 and ending at 2.
  • Line 6: We use the random.randrange() method to return an integer, starting from 2 and ending at 15.
  • Line 8: we use the random.randrange() method to return an integer, starting from 2 and ending at 15, and with a step size of 3.

Free Resources