The Random Module is a pretty popular module in Python. Its most common use is to generate random integers. However, it has various other use cases. We will discuss some of them below
- Random()
- Seed
- Generating a Random Integer
- Generating a Random Multiple of an Integer
- Choosing a random element from an iterable
- Shuffling a List
- Pick n random elements from an iterable
- Generate a random GUID
To use any of the functions below, we will first need to import the random module. It is a built-in module in Python
Random()
This is used to generate a random floating point between 0 and 1
import random
for _ in range(5):
print(random.random())
'''
OUTPUT
0.49871134487223123
0.06941111334065919
0.02980186878132185
0.06790566062222614
0.6563380053516832
'''
Seed
We can set the seed for the random module. Although the integer, float, element from the list will be random. During each run, it'll be the same random value. However, if you use the random module multiple times in a program, it will return a different random value for each call.
random.seed(12)
Generating a Random Integer
This is probably the most popular use case of the random module.
import random
for _ in range(5):
print(random.randint(0,20))
'''
OUTPUT
8
13
4
5
20
'''
The first argument is the start number and the second argument is the end number. It is inclusive,i.e randint() might return the start number or end number as well
Generating a Random Multiple of an Integer
Suppose, we want to generate a random multiple of 10. There are 2 ways to do this
Method 1
We use the randint() function and simply multiply the returned value with 10
import random
for _ in range(5):
print(random.randint(0,20)*10)
'''
OUTPUT
130
20
170
100
200
'''
Method 2
We can use randrange(). We can adjust the start number and end number as needed. It is similar to the randint() function but it takes an additional parameter. It takes the step size. So if we set the step size to 10, it will randomly choose from (0,10,20,30.....)
import random
for _ in range(5):
print(random.randrange(0,100,10))
'''
OUTPUT
130
20
170
100
200
'''
Choosing a random element from an iterable
We can use the random library to chose a random element from an iterable. Note: It will only work with dictionaries if the dictionary has an integer as a key. Read below to find out why
import random
lst = ["hello" , "world" , "!!!" , "Python" , "Medium" , "Hashnod" , "Twitter"]
tpl = ("hello" , "world" , "!!!" , "Python" , "Medium" , "Hashnod" , "Twitter")
dictionary = {idx: val for idx,val in enumerate(lst)}
print(random.choice(lst))
print(random.choice(tpl))
print(random.choice(dictionary))
'''
OUTPUT
world
Hashnod
Medium
'''
The way it works is the following
- First random generates a random integer between 0 and len(iterable)
- It used the generated integer as the index and returns iterabel[index] As a result of this, it works with dictionaries only if the dictionary has an integer as it's key
Shuffling a List
We can use the shuffle() function to shuffle a list. The function can NOT be used with a non-mutable object like a tuple. It is an in-place method, i.e it updates the original list.
import random
lst = ["hello" , "world" , "!!!" , "Python" , "Medium"]
for _ in range(5):
random.shuffle(lst)
print(lst)
'''
OUTPUT
['hello', 'Medium', 'world', 'Python', '!!!']
['world', 'hello', 'Medium', 'Python', '!!!']
['!!!', 'world', 'hello', 'Python', 'Medium']
['Python', 'Medium', '!!!', 'hello', 'world']
['!!!', 'hello', 'Medium', 'world', 'Python']
'''
Pick n random elements from an iterable
This is similar to calling the choice() function in a loop n times. Although, this method doesn't work with dictionaries irrespective of whether they have integers as keys or not
import random
lst = ["hello" , "world" , "!!!" , "Python" , "Medium" , "Hashnod" , "Twitter"]
tpl = ("hello" , "world" , "!!!" , "Python" , "Medium" , "Hashnod" , "Twitter")
dictionary = {idx: val for idx,val in enumerate(lst)}
print(random.sample(lst,3))
print(random.sample(tpl,3))
'''
OUTPUT
['!!!', 'Twitter', 'Medium']
['Hashnod', 'Python', '!!!']
'''
Generate a random GUID
We won't be using the random module anymore, instead, we will use the uuid module
import uuid
print(str(uuid.uuid4()))
print(len(str(uuid.uuid4())))
'''
OUTPUT
6dc2ad9b-2707-45ba-b5e8-5e2eb8a1dfe9
36
'''
uuid4() returns an object of type UUID but we can use str() to typecast it. By default, it produces a 32 character string. We can use string operations to modify the GUID.
import uuid
print(str(uuid.uuid4())[0:16])
print(len(str(uuid.uuid4())[0:16]))
'''
OUTPUT
4bde04c7-d749-40
16
'''
The above code generates a 16 character GUID.
Top comments (0)