What other useful methods does the random module provide?


#1

Question

In the context of this exercise, what other useful methods does the random module provide?

Answer

The random module includes many useful attributes and functionality for tasks that require some randomization. You can see a full list of the attributes in the documentation, or you can use the following functions.

import random

# Prints all attributes of the module
print(dir(random))

# Interactive help pages
help(random)

These are a few methods that the random module provides which can be very useful for certain tasks.

import random

# shuffle() will shuffle a sequence in place
arr = [1, 2, 3, 4]
random.shuffle(arr)
print(arr) # [3, 1, 4, 2]

# random() will return a random float value between 
# 0.0 (inclusive) and 1.0 (exclusive)
print(random.random()) # 0.237...
print(random.random()) # 0.441...

# choices() is similar to choice(), but can return a list of k elements
# from a list, with possibly repeating values.
arr = [1, 2, 3, 4, 5]
print(random.choices(arr, k=3)) # [1, 1, 4]