Working With Random Module in Python

The random module in python is part of the inbuilt python library and you can use this module to generate random numbers and make random selections. In this article, we will discuss different ways to work with the random module in python. For this, we will discuss the functions in this module along with some use cases.

How to Import Random Module in Python?

You can import the random module in python by using the import statement as shown below.

import random

The above syntax brings the random module to the scope of the main program. You can then use all the functions of the random module in python in your program.

To use a function in the random module, you need to call it using the syntax’random.function_name()‘.

For instance, you can use the randrange() function defined in the random module as shown below.

random.randrange(2,15,3)

Instead of using the above syntax, you can import all the functions at once by using the following syntax.

from random import *

After executing the above statement, all the functions in the random module will be imported into your program.

Importing all the functions at once frees you from the need to prefix everything with the literal random as in random.function_name(). After using the above syntax, you can call the function by simply using the function name. However, it also increases the likelihood that a name collision may occur without your knowledge.

It happens because the random module has a function with the same name as its module – ‘random‘. So every time you access the random module in python, you accidentally access the function instead of the module.

So the best way to import the random module in python is by using the syntax ‘import random‘.

Functions in Random Module in Python

In this section, we will discuss different functions defined in the random module in python. After going through this section, you will be able to generate numbers or make a random selection by using those functions.

The random() Function

The random() function is a part of the random library and generates random numbers. This function generates a float value between 0 and 1 without taking any input arguments.

random.random()

You can observe in the following example how the random() function generates a float value.

import random
print ("A random value between 0 and 1 is = ", random.random())

Output:

A random value between 0 and 1 is =  0.773948834014851

In the above example, the random() function has generated the number 0.773948834014851. If you want to generate a number outside the range of 0 and 1, multiply the random function with a multiple of 10, 100, 1000, etc.

import random
print ("A random value between 0 and 100 is = ", random.random()*100)

Output:

A random value between 0 and 100 is =  38.20672649232014

In this example, we have generated a number between 0 and 100 by multiplying the output of the random() function by 100.

Keep in mind that the random module in python only generates pseudo-random numbers. The algorithm does not pick random numbers in true nature, it just gives different results each time.

The randint() Function

You can use the randint() function to generate a random integer that falls within a range. The randint() function takes two inputs – the range’s beginning and the end. After execution, the randint() function returns a random integer that falls inside the specified range.

Let’s look at a piece of code to understand.

random.randint(min value, max value)

The above syntax calls the randint() function. The first input parameter takes the range’s minimum value and the second input parameter takes the range’s maximum value.

To understand the working of the randint() function, let us consider the following program. In the code snippet below, the random module in python is imported as the first line of code. Then, we use a for loop that iterates 3 times using the range() function. Inside the loop, we pass 2 as the first input argument and 7 as the second input argument to the random.randint() function.

import random
# Create a for loop that iterates three times
for i in range(3):
    
    # Use the randint() function to pick a random number from the range
    print ("A random value between 2 and 7 is = ", random.randint(2,7)) 

Output:

A random value between 2 and 7 is =  6
A random value between 2 and 7 is =  2
A random value between 2 and 7 is =  7

In the output, you can observe that the randint() function returns an integer between 2 and 7 each time it is executed. You can use the randint() function to generate random integers, but make sure that the number in the first argument is always smaller than the second argument. Otherwise, the program will run into a ValueError exception.

The choice() Function

The choice() function from the random library selects a random object from a collection object such as a python list. You can use the choice() function on lists, tuples, and dictionaries to get a random selection from the set of objects.

The choice() function takes a collection of objects as its only input argument. It has the following syntax.

random.choice(data_object)

To understand the working of the choice() function, let us consider the following example. Here, the program selects a random element from a list using the choice() function in the code snippet below.

import random
# Create a list with some values
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Use the random.choice() function to pick a random element from the list
random_element = random.choice(my_list)
print("A random element from the list is = ",random_element)

Output:

A random element from the list is =  6

In the first step, we created and passed the list my_list containing 10 numbers to the choice() function. Then, we save the output of the choice() function inside a new variable random_element. Finally, we printed the variable random_element to get the random selection from the list.

Generate a Random Selection From a Dictionary Using the Choice() Function

You can also use the choice() function to get a random selection from dictionaries. The function random.choice() selects a random value from a dictionary in the code snippet below.

import random
my_dict = {'apple': 1, 'banana': 2, 'orange': 3}
# Using random.choice() to randomly select a key-value pair from the dictionary
random_item = random.choice(list(my_dict.items()))
print(random_item)

Output:

('orange', 3)

In the above example,

  • We first imported the random module in python in the first line of code. Then we created a dictionary my_dict with some values. The example uses three fruit names, ‘apple’, ‘banana’, and ‘orange’, and assigns them keys 1, 2, and 3 respectively.
  • Then, we used the random.choice() function to randomly select an item from the python dictionary. For this, we have used the items() method of the dictionary. The inbuilt function my_dict.items() returns a list of items from the dictionary. Here, each item consists of a tuple of a key-value pair.
  • Next, we converted the fetched items from the dictionary into a list using the syntax list(my_dict.items()). After that, pass this list to the random.choice() function.
  • The function random.choice() selects a random item from the contents of the list. Store the returned results inside the variable random_item.

The program randomly picks a fruit name from the dictionary and displays it when the variable random_item is printed.

The shuffle() Function

The shuffle() function, as the name suggests, shuffles the elements of a collection object. It takes a single parameter and returns none. After execution, it modifies the original collection object passed to it as the input argument.

The shuffle() function has the following syntax.

random.shuffle(data_object)

Shuffle a List Using the shuffle() Function

Shuffling a list has never been this easier. All you need to do is create a list, pass it to the random.shuffle() function, and display the results.

Let’s use the random.shuffle() function to shuffle the elements of a list in the code snippet below.

import random
my_list = [1, 2, 3, 4, 5]
random.shuffle(my_list)
print(my_list)

Output

[1, 2, 5, 4, 3]

Here, we have imported the random module in python in the first line of code. Then we created a list my_list and stored five numbers in it i.e. 1,2,3,4,5. Finally, we have passed this list to the random.shuffle() function.

In the output, you can observe that the original list has been modified by the shuffle() function.

Shuffle a Tuple Using the shuffle() Function

You cannot shuffle Python objects like tuples as they are immutable in nature. If you try to shuffle them, this will cause an error in your program. To shuffle them, you need to convert them into a list first. In a similar manner, you don’t need to shuffle a collection object such as a dictionary or a set because they aren’t ordered. Hence, shuffling has no meaning to them.

The following program converts the elements of a tuple into a list and shuffles it.

import random
my_tuple = (1, 2, 3, 4, 5)
# Convert the tuple into a list
shuffled_list = list(my_tuple)
# Shuffle the list
random.shuffle(shuffled_list)
# Pass the shuffled list as a tuple into a new variable
my_tuple = tuple(shuffled_list)
print(my_tuple)

Output:

(3, 4, 1, 5, 2)

In the above program,

  • We first Imported the random module in the first line.
  • Then, we created a tuple my_tuple with five numbers – 1,2,3,4,5.
  • Next, we converted this tuple into a list by using the inbuilt python function – list(my_tuple). We store the output list in the variable shuffled_list.
  • Next, we passed the variable shuffled_list to the random.shuffle() function. This function shuffles the order of elements inside the list. Now we have to convert the list back into a python tuple.
  • Finally, we converted the list shuffled_list back to a tuple using the inbuilt syntax – tuple(shuffled_list).

Hence, the program shuffles the order of the original tuple and displays that shuffled order when the variable my_tuple is printed.

Shuffle a Python Dictionary Using the shuffle() Function

You cannot shuffle a dictionary as this operation has no meaning for the dictionaries. What you can do instead is shuffle the sequence of the keys visible to the user.

Let’s look at a program that extracts the keys from the dictionary and then uses the random.shuffle() function to shuffle the order of the dictionary.

  • First, we will import the random module.
  • Then, we will create a dictionary dict with keys – a, b, and c and assign keys 1, 2, and 3 to them.
  • Next, we will extract the keys from the dictionary and convert them to a list by using the inbuilt function – list(dict.keys()).
  • Then, we will store this newly created list in a new variable keys. After this, we will pass the variable keys to the random.shuffle() function to shuffle its order:
random.shuffle(keys)

After shuffling the keys, we will create a new dictionary shuffled_d with the same key-value pairs as the original one but will replace the keys inside it using dictionary comprehension.

shuffled_d = {key: dict[key] for key in keys}

Now when you print the variable shuffled_d, it shows the elements of the original dictionary but with shuffled order of elements.

You can observe the entire process in the following code example.

import random
dict = {'a': 1, 'b': 2, 'c': 3}
# Get the keys from the dictionary
keys = list(dict.keys())
# Use the shuffle function to shuffle the keys
random.shuffle(keys)
# Create a new dictionary and add the keys in the shuffled order
shuffled_d = {key: dict[key] for key in keys}
print(shuffled_d)

Output:

{'c': 3, 'a': 1, 'b': 2}

The expovariate() Function

The expovariate() function generates a random number from a probability distribution. This function takes a single parameter lambda which is the inverse of the mean of the probability distribution.

For example, if the mean of a probability distribution is 10, then the value of lambda must be 1/10.

The program below generates random numbers using the random.expovariate() function.

import random
# Generate 10 random numbers with a mean of 5
for i in range(5):
    print(random.expovariate(1/3))

Output:

1.1894741926920833
0.5077754248452405
1.7369340998324554
3.1594920943025007
0.2961917047098589

Random Module Code Example

The random module in python generates random values, which is helpful in probability distribution problems. In the example below, the python program uses the random.choice() function to toss two coins and find the results.

  • The first line of code imports the random module in python. Then a list is created storing the two sides of the coin we want to toss – head and tails.
  • We use a for loop using the range() function so that the toss results can be repeated five times. Inside the loop, the variable outcome is passed to the random.choice() function, and the returned result is stored inside the variable toss1.
  • Similarly, inside another variable toss2, the returned result is stored from another execution of the choice() function.
  • Now, when we print the results of toss1 and toss2, we get the outcome of two coins being tossed together.
import random
# Define a list of possible outcomes for a coin toss (heads or tails)
outcomes = ["heads", "tails"]
# Toss two coins and store the results in a list
for i in range(5):
    toss1 = random.choice(outcomes)
    toss2 = random.choice(outcomes)

    # Display the results of the coin tosses
    print("Round: ",i)
    print("Coin 1: {} and coin 2: {}\n".format(toss1,toss2))

Output:

Round:  0
Coin 1: heads and coin 2: tails
​
Round:  1
Coin 1: heads and coin 2: heads
​
Round:  2
Coin 1: tails and coin 2: heads
​
Round:  3
Coin 1: heads and coin 2: tails
​
Round:  4
Coin 1: tails and coin 2: tails

Conclusion

This article explains how you can generate random numbers using the random module in python. You learned how to import a random module, its different functions, and a sample case on how to use this module on a real-life problem.

I hope this article helped you in understanding the random module. To learn more about python programming, you can read this article on python simplehttpserver. You might also like this article on command line arguments using sys.argv in python.

Stay tuned for more informative articles.

Happy Learning!

Leave a Reply