Python - Random Module

The random module is a built-in module to generate the pseudo-random variables. It can be used perform some action randomly such as to get a random number, selecting a random elements from a list, shuffle elements randomly, etc.

Generate Random Floats

The random.random() method returns a random float number between 0.0 to 1.0. The function doesn't need any arguments.

Example: random()
>>> import random
>>> random.random()
0.645173684807533

Generate Random Integers

The random.randint() method returns a random integer between the specified integers.

Example: randint()
>>> import random
>>> random.randint(1, 100)
95           
>>> random.randint(1, 100)
49

Generate Random Numbers within Range

The random.randrange() method returns a randomly selected element from the range created by the start, stop and step arguments. The value of start is 0 by default. Similarly, the value of step is 1 by default.

Example:
>>> random.randrange(1, 10)
2
>>> random.randrange(1, 10, 2)
5            
>>> random.randrange(0, 101, 10)
80

Select Random Elements

The random.choice() method returns a randomly selected element from a non-empty sequence. An empty sequence as argument raises an IndexError.

Example:
>>> import random
>>> random.choice('computer')
't'          
>>> random.choice([12,23,45,67,65,43])
45           
>>> random.choice((12,23,45,67,65,43))
67

Shuffle Elements Randomly

The random.shuffle() method randomly reorders the elements in a list.

Example:
>>> numbers=[12,23,45,67,65,43]
>>> random.shuffle(numbers)
>>> numbers
[23, 12, 43, 65, 67, 45]
>>> random.shuffle(numbers)
>>> numbers
[23, 43, 65, 45, 12, 67]

Learn more about the random module in Python docs.

Want to check how much you know Python?