• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
PythonForBeginners.com

PythonForBeginners.com

Learn By Example

  • Home
  • Learn Python
    • Python Tutorial
  • Categories
    • Basics
    • Lists
    • Dictionary
    • Code Snippets
    • Comments
    • Modules
    • API
    • Beautiful Soup
    • Cheatsheet
    • Games
    • Loops
  • Python Courses
    • Python 3 For Beginners
You are here: Home / Random / How to Use the Random Module in Python

How to Use the Random Module in Python

Author: PFB Staff Writer
Last Updated: June 15, 2023

We often need to make random selections or generate random values while programming in Python. In this post, I will describe the use of the random module in Python. The random module provides access to functions to generate random numbers and strings. It also provides functions to select random elements from a list or shuffle a list. We will discuss each function one by one.

Table of Contents
  1. When to Use the Random Module in Python?
  2. Random Functions in Python
    1. The randint() Function in Python
    2. The random() Function
    3. The choice() Function
    4. The choices() Function
    5. The shuffle() Function
    6. The randrange() Function
  3. Code Example For Random Module in Python
  4. Conclusion

When to Use the Random Module in Python?

The random module provides functions that help in making random selections and generating random values. Hence, we can use the random module in Python in the following cases.

  • If you want the computer to pick a random number in a given range, pick a random element from a Python list, pick a random card from a deck, flip a coin, etc, you can use the random module in Python.
  • You can also use the random module to create random strings while choosing passwords to make your password database more secure or power a random page feature of your website.
  • Random modules provide functions to shuffle container objects like lists. Hence, you can use the random module to shuffle a list.

Random Functions in Python

The Random module contains some very useful functions. The most commonly used functions in the random module in Python are the randint() function, the random() function, the choice() function, the randrange() function, and the shuffle() function. Let us discuss each of these functions one by one.

The randint() Function in Python

We can use the randint() function in the Python random module to generate random numbers within a range. The randint() function takes two numbers as its input argument. The first input argument is the start of the range and the second input argument is the end of the range. After execution, the randint() function returns a random integer within the given range.

If you want a random integer, you can use the randint() function. For instance, you can generate random integers between 1 and 10 as shown in the following example.

import random
integer1=random.randint(1,10)
integer2=random.randint(1,10)
integer3=random.randint(1,10)
integer4=random.randint(1,10)
print("The random integers between 1 and 10 are:",integer1, integer2, integer3, integer4)

Output:

The random integers between 1 and 10 are: 9 8 10 1

In the above code, we have created four random integers between 1 and 10. You can observe that the randint() function generates a different integer each time we execute it. However, this is not guaranteed. It is also possible that the function may generate the same number on consecutive executions. However, it is sure that the numbers generated afterward have no relation whatsoever with the previous numbers generated using the randint() function.

In the above code, you should make sure that the first input argument in the randint() function should always be less than the second input argument. Otherwise, the program runs into an error. You can observe this in the following example.

import random
integer1=random.randint(10,1)
print("The random integers between 1 and 10 is:",integer1)

Output:

random module example in Python
random module example in Python

In the above image, you can observe that the program runs into error if we pass the first input argument greater than the second input argument in the randint() function.

The random() Function

The random() function in the random module is used to generate random numbers between 0 and 1. When we execute the random() function, it returns a floating point number between 0 and 1. You can observe this in the following example.

import random
number1=random.random()
number2=random.random()
number3=random.random()
number4=random.random()
print("The random numbers are:",number1, number2, number3, number4 )

Output:

The random numbers are: 0.2801382415422472 0.48619684476217817 0.5339393721250865 0.9565177646505902

In the above output, you can observe that the random() function generates a random value between 0 to 1 each time it is executed.

If you want a larger number, you can multiply the values generated from the random() function by a larger value. For example, to create a random number between 10 and 100, you can multiply the output of the random() function by 100 as shown below.

import random
number1=random.random()*100
number2=random.random()*100
number3=random.random()*100
number4=random.random()*100
print("The random numbers are:",number1, number2, number3, number4 )

Output:

The random numbers are: 51.43882585961895 59.29311262613833 37.44226472488235 50.768817583443315

In the above example, we have created random numbers between 10 and 100 by multiplying the output of the random() function by 100. In a similar manner, you can multiply the output of the random() function by negative numbers to generate negative values.

The choice() Function

The choice() function is used to select a random element from a collection object like a list, set, tuple, etc. The function takes a collection object as its input argument and returns a random element.

For example, you can select a random color from a list of colors by passing the list of color names to the choice() function as input as shown in the following example.

import random
colors=["red","green","blue","yellow","violet","indigo","orange"]
print("The list of colors is:",colors)
color=random.choice(colors)
print("The randomly selected value from the list is:",color)

Output:

The list of colors is: ['red', 'green', 'blue', 'yellow', 'violet', 'indigo', 'orange']
The randomly selected value from the list is: orange

In the above example, we first created a list of seven color values. Then we passed it to the choice() function defined in the random module in Python to select a random value from the list.

If we pass an empty list to the choice() function, it runs into a Python IndexError exception as shown below.

import random
colors=[]
print("The list of colors is:",colors)
color=random.choice(colors)
print("The randomly selected value from the list is:",color)

Output:

IndexError: list index out of range

The choices() Function

We can use the choices() function defined in the random module in Python to select two or more elements randomly with replacement from a list. The choices() function takes the list of values as its first input argument and the values to be selected as the input for its parameter k. After execution, it returns a list of selected values from the input container object.

For example, you can select three values from the list of colors using the choices() function as shown below.

import random
colors=["red","green","blue","yellow","violet","indigo","orange"]
print("The list of colors is:",colors)
color=random.choices(colors,k=3)
print("The randomly selected values from the list are:",color)

Output:

The list of colors is: ['red', 'green', 'blue', 'yellow', 'violet', 'indigo', 'orange']
The randomly selected values from the list are: ['blue', 'orange', 'orange']

In the above example, you can observe the output list of values contains the value 'orange' twice. This is due to the reason that the choices() function makes a random selection with replacement. Hence, a value can be repeated two or more times in the output list.

If you pass the value k=0 to the choices() function, it will return an empty list as shown below.

import random
colors=["red","green","blue","yellow","violet","indigo","orange"]
print("The list of colors is:",colors)
color=random.choices(colors,k=0)
print("The randomly selected values from the list are:",color)

Output:

The list of colors is: ['red', 'green', 'blue', 'yellow', 'violet', 'indigo', 'orange']
The randomly selected values from the list are: []

Even if we set k larger than the number of elements in the input list, the choices() function produces the output list as shown below.

import random
colors=["red","green","blue","yellow","violet","indigo","orange"]
print("The list of colors is:",colors)
color=random.choices(colors,k=20)
print("The randomly selected values from the list are:",color)

Output:

The list of colors is: ['red', 'green', 'blue', 'yellow', 'violet', 'indigo', 'orange']
The randomly selected values from the list are: ['yellow', 'orange', 'orange', 'violet', 'orange', 'violet', 'red', 'violet', 'green', 'violet', 'indigo', 'violet', 'yellow', 'red', 'red', 'indigo', 'red', 'red', 'green', 'green']

In this example, we have only seven elements in the input list. However, the choices() function has given a list containing 20 elements as its output. This is due to the reason that the choices() function makes a selection with replacement. Hence, an infinite number of selections can be made from the input list.

If the input list to the choices() function is empty, the choices() function creates an empty list when we ask it to select 0 elements from the list. You can observe this in the following example.

import random
colors=[]
print("The list of colors is:",colors)
color=random.choices(colors,k=0)
print("The randomly selected values from the list are:",color)

Output:

The list of colors is: []
The randomly selected values from the list are: []

In the above example, the input and output lists both are empty. However, if we try to select one or more elements from an empty list using the choices() function, the program will run into an error. You can observe this in the following example.

import random
colors=[]
print("The list of colors is:",colors)
color=random.choices(colors,k=2)
print("The randomly selected values from the list are:",color)

Output:

IndexError: list index out of range

In this example, we tried to select two elements from an empty list. Hence, the program runs into an IndexError exception.

The shuffle() Function

As the name suggests, the shuffle() function shuffles the elements in the list in place. The shuffle() function takes a list as an input argument. After execution, the elements of the list are shuffled in a random order as shown in the following example.

import random
colors=["red","green","blue","yellow","violet","indigo","orange"]
print("The list of colors is:",colors)
random.shuffle(colors)
print("The list of colors after shuffle is:",colors)

Output:

The list of colors is: ['red', 'green', 'blue', 'yellow', 'violet', 'indigo', 'orange']
The list of colors after shuffle is: ['green', 'indigo', 'blue', 'violet', 'yellow', 'orange', 'red']

In the above output, you can observe that the order of the elements in the colors list has changed after executing the shuffle() function.

The randrange() Function

The randrange() function in the Python random module is used to select a random element from a given range. It takes three numbers namely start, stop, and step as input argument. After execution, it generates a randomly selected element from the range(start, stop, step). You can observe this in the following example.

import random
number=random.randrange(0,100,20)
print("The random number is:",number)

Output:

The random number is: 20

In the above example, the randrange() function will always generate one of the values from [0,20,40,60,80]. You can observe this in the following example.

import random
print("The numbers are")
for i in range(50):
    number=random.randrange(0,100,20)
    print(number, end=" ")

Output:

The numbers are
20 40 60 60 60 20 80 60 80 0 20 60 80 80 80 20 80 40 20 60 40 60 40 0 0 40 20 80 0 60 40 40 40 20 80 0 40 80 20 0 80 20 40 60 0 40 20 0 40 80 

In the above example, you can observe that the values in the output are from the list [0, 20, 40, 60, 80]. What explains this behavior of the randrange() function?

Effectively, the randrange() function works as a combination of the choice() function and the range() function. First, it generates numbers in the given range with the given intervals using the range() function. To understand the working of the range() function, you can read this article on Python range. After generating numbers in the given range, it uses the choice() function to select a random value in the given range.

Code Example For Random Module in Python

The following code example uses the choice() function to count the number of heads and tails in 10000 flips of a coin. For this, we define a dictionary named outcomes to store the number of heads and tails. Next, we use the keys() method of the Python dictionary to get the list ["heads", "tails"]. After this, we use the choice() function to select one of the values from the list randomly and update the outcomes dictionary according to the output.

import random
import itertools

outcomes = { 'heads':0,
             'tails':0,
             }
sides = outcomes.keys()
for i in range(10000):
    outcomes[ random.choice(sides) ] += 1
print 'Heads:', outcomes['heads']
print 'Tails:', outcomes['tails']

There are only two outcomes allowed, so rather than use numbers and convert them, the values โ€œheadsโ€ and โ€œtailsโ€ are used with the choice()function.

The results are tabulated in a dictionary using the outcome names as keys.

Heads: 4984
Tails: 501

Conclusion

In this article, we have discussed different functions in the random module in Python. We have also discussed a code example using the choice() function to simulate coin flips.

To learn more about Python programming, you can read this article on list comprehension in Python. You might also like this article on string manipulation.

I hope you enjoyed reading this article. Stay tuned for more informative articles.

Happy Learning!

Related

Recommended Python Training

Course: Python 3 For Beginners

Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.

Enroll Now

Filed Under: Random Author: PFB Staff Writer

More Python Topics

API Argv Basics Beautiful Soup Cheatsheet Code Code Snippets Command Line Comments Concatenation crawler Data Structures Data Types deque Development Dictionary Dictionary Data Structure In Python Error Handling Exceptions Filehandling Files Functions Games GUI Json Lists Loops Mechanzie Modules Modules In Python Mysql OS pip Pyspark Python Python On The Web Python Strings Queue Requests Scraping Scripts Split Strings System & OS urllib2

Primary Sidebar

Menu

  • Basics
  • Cheatsheet
  • Code Snippets
  • Development
  • Dictionary
  • Error Handling
  • Lists
  • Loops
  • Modules
  • Scripts
  • Strings
  • System & OS
  • Web

Get Our Free Guide To Learning Python

Most Popular Content

  • Reading and Writing Files in Python
  • Python Dictionary โ€“ How To Create Dictionaries In Python
  • How to use Split in Python
  • Python String Concatenation and Formatting
  • List Comprehension in Python
  • How to Use sys.argv in Python?
  • How to use comments in Python
  • Try and Except in Python

Recent Posts

  • Count Rows With Null Values in PySpark
  • PySpark OrderBy One or Multiple Columns
  • Select Rows with Null values in PySpark
  • PySpark Count Distinct Values in One or Multiple Columns
  • PySpark Filter Rows in a DataFrame by Condition

Copyright © 2012–2025 ยท PythonForBeginners.com

  • Home
  • Contact Us
  • Privacy Policy
  • Write For Us