Python Random Methods Tutorial

Python has a random module that provides different random methods to generate random numbers, random selection, etc. Even the random() method is the most popular method to generate a random number there are alternative methods to generate random values.

Random Methods

As a dynamic and rich programming language Python provides different random methods. Even 3rd party Python libraries and modules like NumPy etc provide random methods. Below we list some popular and useful random methods provided by Python by default.

  • random()
  • randint()
  • randrange()
  • uniform()
  • shuffle()

Seed The Randomness Before Generating Random Values

Randomness is a magic work where it should be seeded with a random values. As digital world most of the things can be predicted and do not provide complete randomness we should use the random.seed(1) method to create a need seed for random methods after importing the random module.

import random


random() Method

The most popular method in random methods is the random() method. It simply generates a random number between 0 and 1. As expected this number is a floating-point number. The random() method does not require any parameter.

import random




randint() Method

The randint() method is used to generate random numbers for the specified range. The syntax of the randint() method is like below. The range should be an integer and generated random is also integer between range too.

  • START is the lowest number that can be generated as a random number.
  • STOP is the highest number that can be generated as a random number.

We can generate random integers for the specified range like below.

import random






randrange() Method

The randrange() method is another method which can be used to generate random integers. The difference is that the step can be specified where only specific numbers are generated randomly. For example we want to generate random numbers between 2 and 10 but we want them to be odd. So we can sepecify the step as 2 and the generated random number is selected from 2,4,6,8,10.

import random




uniform() Method

The uniform() method is used to generate random floating point numbers. The uniform() method accepts two parameters and uses following syntax.

  • START is the start of the random floating-point range.
  • END is the end of the random floating-point range.

In the following example we will generate floating point random numbers between 5 and 10.

import random




shuffle() Method

The random module also provides the ability to shuffle randomly the given list. This is implemented with the shuffle() method. The shuffle() method randomly shuffles all items from the provided list. The list is provided as a parameter to the shuffle() method.

import random


list = [1,2,3,4,5]

//[1, 3, 2, 5, 4]

//[2, 5, 4, 1, 3]

Leave a Comment