Random library in python is an important library used to generate random options for the user to use in a program. It can be imported in the working file with all its methods accessible to the user where pseudo-random numbers are generated for different distributions.
What is Python Random Module?
Random module comes built-in with python which means that we do not need to install a package but just import and use it on the go. Python Random Module is useful in implementing a randomization algorithm. It can be used for generating integers from a specified range to pick the number from. Also, we have the feature to choose from a sequence of numbers of choice we can pick from a list of elements.
However, it generates the numbers in a pseudorandom manner that is not completely random if we deep dive further into its working mechanism under the hood but still remains effective for usage. Different functions from the Python Random Module are going to be discussed in this article with examples and explanations for each.
Seeding can be performed using seed() function where on seeding, the same value will be generated. It is used as a tool to initialize the value generator to reset in an algorithmic manner that once seeded, the sequence of values obtained remains the same.
Given below is an example of seeding in Python Random Module.
Example of Python Random Module:
import random # Seed the random number generator random.seed(2) # Generate 4 random numbers for i in range(4): print(random.random()) random.seed(2)
0.9560342718892494 0.9560342718892494 0.9560342718892494 0.9560342718892494
Generating Random Numbers
Now that we have some idea about the python random module, we will be looking at how to generate numbers of different types using the methods of random library.
Float Value Between 0 and 1:-
In the below code mentioned, we can use the random() function to generate a float value between the range 0.0 and 1.0 such that value must me greater than or equal to 0.0 and strictly lesser than 1.0.
import random # Generating random float print(random.random())
Integer Between Input Range:-
If we want to generate a random integer in a certain range then the randint() function proves to be the ideal that takes in two inputs, suppose a and b, and generates one between the two integers. It includes a and b as well in the result.
import random #Generating Random integer print(random.randint(1, 10))
Float Between Input Range:-
Similarly to generating integers between two input values, assumingly, a and b, we can generate a float value between the two inputs using uniform() function. The code below can be referred to for same.
import random #Generating Random float print(random.uniform(1, 10))
Working with Sequences
The application of the Python Random module is not limited to single values such as integer or float as we can use it to work on sequences as well.
Random K Elements From List (Without Replacing)
In case we have a list container and we want to pick only k values from it such that all of them are randomly picked without replacement, we can use sample(l,k) where l is the list container with elements and k is the number of required elements.
import random items = [ 2, 3, 4, 5, 37, 8, 9, 10] print(random.sample(items, 3))
[37, 9, 5]
Random K Elements From List (With Replacing Items)
In such a scenario where a sequence and k random values need to be picked, replacing the element then choice() function is the alternative to the sample() function where the same element can be picked multiple times. Give Python Random K elements from list code is given below:-
import random items = [2, 3, 4, 25, 7, 38, 9] print(random.choices(items, k=3))
[2, 3, 3]
To shuffle the list with random ordering, the shuffle() function can be used to perform the operation.
import random # Shuffling Sequences items = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10] random.shuffle(items) print(items)
[5, 8, 6, 11, 3, 10, 9, 4, 7, 2]
Generating Random Strings
The Python Random module is helpful in generating random strings of certain length provided as input by the user. The strings can be of different bases depending upon the function with code below where a hexadecimal string of length 10 is generated and 10 is encoded into base64 and a string value is returned.
import random # Generating Random Strings print(random.hex(10)) print(random.b64encode(10))
Code – Password Generator Using Random Module
As we are done studying about the random module and what it can do with the function that it offers. Let us implement it in a real-world application by designing a password generator.
import random import string # Generating Random Passwords def generatePassword(n): characters = string.ascii_letters + string.digits + string.punctuation password = ''.join(random.choices(characters, k=n)) return password print("Enter the length of password you want to generate:-") while True: password = generatePassword(int(input())) print("Your password is: ",password) inp = input("Do you agree with password. Press Y or N - ") if inp == "Y": print("Password was changed!") break
Enter if you want to generate password:- Your password is: vB%N&N[TG[eK6zF#Nl-@ Do you agree with password. Press Y or N - Y Password was changed!
Password generator function takes an input that provides the length of password to be generated. It forms a string consisting of numbers, letters and punctuations such that the string is interpreted as the sequence to pick the random values from in it. choice() function is used giving the length of password to generate the password. As the prompt shows, if we want to go ahead with the password, we can go ahead or break out.
In this article, we studied about the Python Random module and the use cases such as generating random numbers of different types, random sampling from a sequence, both unique and repetitive and shuffling of list. We also used the Python Random module for creating a password generator to be well-versed with the module. We hope you liked this article and hope to see you again at PrepBytes with another informative article.
Frequently Asked Questions
1. Does the Random module need installation to use?
No. Random module in python requires no installation as it comes built-in with Python and can be used directly by importing the required functions or whole module into the working file.
2. What is shuffling in the Python Random module?
Shuffling is done on a list such that the position of items in the list is rearranged randomly. It is possible to shuffle a list using the shuffle() function of a random module.
3. What is seed and how does it work?
Seed is a function that is used to initialize the random generator in an algorithmic manner where the same sequence of numbers is produced for the value passed with the function.
4. What must be the type of seed value?
Seed value must remain to be an integer as it does not support to seed the generator for a value of different type.
5. State the applications of the Python Random module.
It is used in fields such as Simulation, Gaming, Machine learning, Testing, Cryptography and Data Analysis etc. Randomization algorithms such as Las Vegas and Monte Carlo are few of the other applications.