What other useful methods does the random module provide?

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]
9 Likes

4 posts were split to a new topic: Why doesn’t random.choices work?

If random.random() returns a random float value between 0 and 1, wouldn’t that returned number take up infinite space? Does it stop at a certain number of digits?

1 Like

One could be mistaken but I believe floats are stored as 32 bits: a sign bit, eight bits for an exponent, and 23 bits for the significand. Let me see if I can find something on this…

c - Can anyone explain representation of float in memory? - Software Engineering Stack Exchange

I’m guessing the Python follows the same rules as C. There is a limited amount of space, so it follows there will be a limited number of digits. On the screen we usually see around 17. For our purposes in generating pseudo random numbers this is plenty sufficient. No matter what number is generated they all take up the same amount of space in memory.

4 Likes

Meaning 1 and 100 trillion take up the same amount of space? That’s counter intuitive. Why don’t larger numbers require more memory?

The numbers are not stored, only the first value/subsequent, endpoint and a counting method.

1 Like