Python's Random Module
Learn some important methods for Python's built-in random module.
Introduction
Python has many built-in packages for developers to use. These packages are basically files full of code that you can use without typing the actual algorithms and concepts. Usually, a package consists of some functions or classes that a developer can call or initialize, respectively. Creating a package isn't restricted to developers at Python though. People from the outside can create their own Python packages (also referred to as a library or module) and upload them to the internet for other people to download. Several popular external Python packages include Pandas, NumPy, PyGame, etc. In this article, you will learn about Python's built-in random module.
Random
Python's random module is a module for generating pseudo-random numbers and choices from multiple data structures and types. Since random is built-in, there's no need to install anything. It's useful to note that when a package needs to be installed, the default package manager for Python is PIP. Let's take a look at some functions in the random module.
Importing
To use any Python library, a developer needs to install it, built-in or not. To do this you would use the following line of code.
import package_name
from package_name import some_class, some_method, some_variable
from package_name import *
import really_long_package_name as short_name
from package_name import really_long_class_method_or_variable_name as short_name
The easiest way to import a package is just by using the keyword import
followed by the name of the package. Remember that if you import this way, any class, function, or variable will need to be accessed by typing package_name.method
or .class
or .variable
. You get the idea.
What if the package you want to use has methods, classes, or variables you will use multiple times throughout your entire program? Or if the name of the package is really long? There are a couple of different ways to solve this problem.
The first would be importing each thing you need from the class separately using the from
keyword. Let's say you have a package with many different things but you only need to use a couple. you would use the from
keyword to import only the things you are planning to use. The second line of the code above is how to do that. Just say from package_name
and then import classes, modules, variables
separate by a comma for each thing.
The second one would be importing every method separately from the module. Instead of typing each thing you need, you can type an *
and the interpreter will import everything in that module. Useful to not have to type package_name.
for everything.
randint(start, end)
- Random Numbers
This method can generate random numbers from a given range.
# Import the Module
import random
# Prints out a random integer between 0 and 10 (inclusive)
print(random.randint(0, 10))
# Possible Outputs ^ - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
As you can see, this method is very simple. Type out the method with whatever import style you used for the package and then type in the arguments for the function. You have a start and an end. The output will be a random number between the two arguments, including those two. Let's move on!
randrange(start, end, step)
- Random Numbers with Steps
This method can generate random numbers and an optional step between.
# Import the Module
import random
# Prints out a random integer between 0 and 9 (one less than end)
print(random.randrange(0, 10))
# Possible Outputs ^ - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
# Print out a random integer between 0 and 9 with a step of 2
print(random.randrange(0, 10, 2))
# Possible Outputs ^ - 0, 2, 4, 6, 8 (start then add step for next int)
This method is a bit different from randint()
. randrange()
takes three arguments, the third being optional. Without the step argument, randrange()
is basically randint(start, end - 1)
. Or is it the other way... With the step argument, randrange()
's possible outputs will include the starting number then +step, and so on. If the next plus two isn't part of end - 1, then that output won't be there.
choice(sequence)
- Random Choice from Sequence
This method can select a random choice from a sequence such as a list, tuple, range, string, etc.
# Import the Module
import random
# Print out a random selection from a list of choices
sports = ['soccer', 'basketball', 'football', 'volleyball']
print(random.choice(sports))
# Possible Outputs ^ - any choice from the list sports
# Print out random character from string
string = 'python'
print(random.choice(string))
# Possible Outputs ^ - any charcter from the value of string
# Print out random choice from multi-type list
multi_type = ['soccer', True, 1, 8.234, 46, False]
print(random.choice(multi_type))
# Possible Outputs ^ - any choice from the list multi_list
This method can be extremely useful in some cases. Let's say you have a program that can select a random password or username. You can use random.choice()
.
shuffle(sequence)
- Shuffle a Sequence
This method shuffles a given sequence. The types allowed are the same as random.choice()
except for strings.
# Import the Module
import random
# Print out an ordered list, but shuffled
ordered_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(random.shuffle(ordered_list))
# Example Output ^ - [6, 3, 7, 2, 8, 1, 5, 9, 4, 10]
Pretty straightforward, right? The output of this method is the input but shuffled randomly. It's like shuffling a new deck of cards.
sample(sequence, length)
- Collect a Sample
This method returns another sequence of a given length with random choices from a given sequence. By sequence, I mean anything allowed by shuffle()
. The length argument can't be greater than the passed sequence's size or an error will be printed.
# Import the Module
import random
# Print out a sample of a list full of numbers
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(random.sample(nums, 5))
# Example Output ^ - [1, 5, 4, 9, 6]
As you can see, the output will be a sample of the given sequence with a size of the given length. random.sample()
can be useful for many projects. Like, let's say you are making a quiz app and you have a list of questions. You can randomly select a bunch of questions from that list with random.sample()
! Each index in the list is unique so wouldn't need to worry about duplicate questions!
Conclusion
The random module of Python is an amazing built-in tool for developers to randomize anything. Almost every day we make a random decision. What apple to eat? What formula should I use? Computers do the same. Almost every app you see today incorporates some randomization. Whether it's Google's random password picker or an app's random username selector/suggester. Now you can do it yourself!