How To Use The Random Module in Python

Python has many built-in modules or library which helps us with different functions or services. First when we say module or library, it is a collection of code library. We can relate it with a physical library, which holds different books which we served from it, python modules are also similar to that they help us with different functions.

So, one of those python modules is what we are going to see for now, which is the Random module, that we use to make random numbers or elements in different ways.

What Is The Python Random Module

This random module has several Methods and select an element(s) randomly from a non-empty sequence in different ways.
we are going to see some of them in the following format:

  • Name of the method
  • Their description
  • Their function and implementation
  • An example

In this article I will show a real example of random.choice() method that I use work to select names randomly from a list and assigns them with a randomly selected tasks.
First, let’s see pythons random randint() and randrange() methods to generate integer numbers from a given range randomly.
For example, let say you want to generate a random integer number between 10 to 20, you can use both randint() and randrange(), but we have to be careful which one to use, since they have a difference, we will see them one by one:

random.randint():

				
					syntax:

random.randint(start, stop)
				
			

This randint() method requires both start and stop parameters. It returns then a random integer number given between start and stop and both are included.

Example:
random.randint(10, 20) return a random number between 10 & 20 (both 10 and 20 included)
You can have a good understanding from the following examples.
Again we don’t have to use numbers other than integers example, float: if used it will give you value error.

How To Use random.randint():

				
					import random

print("Random number from 10 to 20")
x1 = random.randint(10, 20)
print("Random number: ", x1)

print("--------------------")

print("Random number from 50 to 100")
x2 = random.randint(50, 100)
print("Random integer: ", x2)

#Output:
#Random number from 10 to 20
#Random number: 18
#--------------------
#Random number from 50 to 100
#Random integer: 84

				
			

random.randrange():

				
					syntax:

random.randrange(start, stop[, step])
				
			

This random.randrange takes three parameters, in which, two of them are optional, these are the start and step are optional.
It generates a randomly selected number from the range, random.randrange(start, stop, step), in which stop is excluded.

Start parameter: is the starting number of the range. If not specified it will be 0 (zero) by default.
Stop parameter: is the last number in the range
Step parameter: is the different value between each number in elements or list that has to be returned. This parameter is optional. And if it is not specified as a parameter, the step value will be 1 by default.

Example:
Random.randrange(4, 18, 2), this will return:
Any random number between 4 and 18 in step of 2, like this; 4, 6, 8, 10……16, but 18 will not be returned in this case, because randrange() method doesn’t allow to return the last number in the range.

How To Use random.randrange():

				
					import random

print ("Generating random nunber between 5 and 15 ")

r= random.randrange(15)

print(*Random number: ", 71)

print ("Generating random nunber between 10 and 20")

72 = random.randrange(10, 20)

print(*Random number: ", 2)

print(“Generating random number between 30 and 95 divisible by 5")
73 = random.randrange(30, 95, 5)

print("Random number: ",'r3)

#Output:
#Generating random number between 5 and 15

#Random number: 2

#Generating random nunber between 10 and 20

#Random nunber: 11

#Generating random nunber between 30 and 95 divisible by 5
#Random number: 5S

				
			

From this above example, we see that the first one has only on argument, which means it is the last number, then the start number is zero by default, so any number including zero has equal probability to be selected except 15.
In the 2nd example, both start & stop numbers are given, so, any number between them has also equal probability to be returned, excluding the last number, in this case 20.
In the 3rd example, 3 arguments are given, in this case any number between 30 & 95 but in step of 5 has equal chance of selecting except 95.

random.choice():

Now, let’s see the random.choice(), radom.choices(), and random.sample() and their difference. After that we gonna see a real example with random.choice we used at work.

As we already saw in the above, random.randint(), and random.randrange() functions are used to return from a given range of integers, random.choice() function is used to select random element from a list, string or tuple which is from non-empty sequence.

				
					syntax:

random.choice(sequence)  
#a sequence = string or list or a tuple

				
			
  • This random.choice() function returns a single element from the list
  • Can’t choose from an empty list or string
  • Passing an empty list to this function gives IndexError
				
					import random
names = ["John", "Michael", "Samuel","Peter", "George", "Stephanos"]
print("The random name selected from the name list is: ", random.choice(names))
				
			

Each name in the list has equal probability to be selected randomly, i.e.: 16.7%

Suppose we want to select multiple elements from a list, so, random.choice() is not an option, to do that we can use either random.choices(), or random.sample().
Both:

  • Select multiple elements that we want
  • Elements can be repeated if we use random.choices() , while
  • Elements returned using random.sample() will not be repeated or no duplication.

Let’s see them one by one:

random.choices():

This function selects multiple elements depending on the sampling size you give.
Here, each element will have different probability of selection.

				
					syntax:
random.choices(sequence, k) 
#k is optional here

				
			

In this case, it is possible to specify “k” to select multiple elements from the list, otherwise it will return only one element.

				
					import random
names = ["John", "Michael","Samuel", "Peter", "George", "Stephanos"]

print("the randomly selected names from the name list are: *, random.choices(names, k:3))

				
			

random.sample():

Same as random.choices() function, random.sample() function also selects multiple elements from a given list, but without repeating any element.

				
					syntax:
random.sample(sequence, k) 
#k is a must here

				
			

Random.sample requires two arguments, as we see in the above syntax:
“k” is the sampling size, the number of elements we want to select. If you don’t specify “k” it will raise a type Error: missing 1 required positional argument.

Example:

				
					import random
names = ["John","Michael”,"Samuel”,"Peter","“George”, “Stephanos”]
print("The randomly selected names from the name list are: ", random.sample(names))

#Try to run the code yourself. You'll get an error!

				
			

To correct the error in the example above, you must include “k”. K stands for the amount of samples.
Here is the correct way:

				
					import randon
names = ["John", "Michael", "Samuel", "Peter", "George", "Stephanos"]
print("The randomly selected names from the name list are: ", random.sample(names, k=4))

				
			

The Task Generator

At last, let me show you the real example I used to select names of employees randomly and assign a task for each one randomly without repeating anyone.

Importing the random module:

				
					import random
				
			

Employee names list:

				
					participants = ["Thein Soe", "Colin", "Sabreen","Habtom", "Ohmar", "Elias", "Hamada", "Teklia", "Nazzal", "Maisa", "Senere", "Jebid", "George", "Kristle"]

choices = ["Vacuum", "Take Trash Out Monday", "Take Trash Out Tuesday", "Take Trash Out Thursday", "Water Plants", "Take Paper and Glass Recycling Out", "Wipe Down Tables Monday", "Wipe Down Tables Tuesday", "Wipe Down Tables Thursday", "Put Tables and Chairs Back Monday", "Put Tables and Chairs Back Tuesday", "Put Tables and Chairs Back Thursday", "No task for you this week", "No task for you this week"]

				
			

The result of the code i.e. randomly selected names with a task assigned to them:

				
					while choices:
select = random.choice(participants)
print(“selected person is :", select)
participants.remove(select)

assign = random.choice(choices)
print("assigned task is :", assign)
choices.remove(assign)
print("--------------------")

#output
#selected person is : Elias
#selected task is : Put Tables And Chairs Back On Thursday
#--------------------
#selected person is : Habtom
#selected task is : Water Plants
#--------------------
#You catch my drift.
				
			

Therefore, this random module specially random.choice has an amazing function in the real working ground. We can even use it for example in football, champions league knockout round and such similar tasks.

Skip to content