Exploring the Python Random Module

The random module in Python provides a suite of functions for generating random numbers, shuffling sequences, and performing other random operations. In this guide, we will explore how to use the random module to generate random numbers, select random items, shuffle lists, and more.



Importing the Random Module

Before using any of the functions in the random module, we need to import it into our Python program. The random module is part of Python's standard library, so you don't need to install anything extra—just import it and start using it.

python

# To import the random module
import random

# Now you can use any function from the random module, like random.randint() or random.choice()

Once the random module is imported, you can call its functions using the random. prefix. For example, to generate a random integer, you would write random.randint(1, 10), or to pick a random item from a list, you can use random.choice(my_list).

Here's an example of how to generate a random number between 1 and 100 using the random.randint() function:

python

import random

# Generate a random integer between 1 and 100
random_number = random.randint(1, 100)
print(random_number)  # Output: A random integer between 1 and 100

As shown above, once the module is imported, you can use it freely throughout your code. The random module provides a variety of functions for different randomization tasks.


Random Module Functions

The random module contains several functions for generating random numbers and manipulating sequences. Below are some of the most commonly used functions:

1. Generating a Random Number with randint()

To generate a random integer within a specified range, use the randint function from Python’s random module. This function returns a random integer between the two numbers you provide (inclusive).

python
import random

random_number = random.randint(1, 10)
print("Random number between 1 and 10:", random_number)

How It Works:

  • import random: This line imports Python’s built-in random module, which provides functions for generating random numbers.
  • random.randint(1, 10): This function call generates a random integer between 1 and 10, including both 1 and 10.
  • The result is stored in the variable random_number.
  • print(...): This prints the random number along with a message to the screen.

Possible Output

Random number between 1 and 10: 7

2. Using random() to generate a random floating-point number

The random() function from the random module generates a random floating-point number between 0 and 1.

python
import random
print(random.random())

How It Works:

  • random(): This function generates a random floating-point number in the range [0.0, 1.0). This means the number is always greater than or equal to 0 and less than 1.
  • print(random.random()): This prints the random number generated to the screen.

Output

0.7361398574720124

3. Using choice() to select a random element from a list

The choice() function randomly selects one item from a non-empty sequence (like a list).

python
import random
fruits = ['apple', 'banana', 'cherry', 'grapes']
print(random.choice(fruits))

How It Works:

  • fruits: A list containing some fruit names.
  • random.choice(fruits): This picks a random element from the fruits list and returns it.

Output

banana

4. Using shuffle() to shuffle a list

The shuffle() function randomly shuffles the elements of a list in place.

python
import random
numbers = [1, 2, 3, 4, 5]
random.shuffle(numbers)
print(numbers)

How It Works:

  • numbers: A list of integers.
  • random.shuffle(numbers): This shuffles the list numbers in place, meaning the original list is reordered randomly.
  • Note: The shuffle() function does not return a new list. It modifies the list directly.

Output

[4, 1, 3, 5, 2]

5. Using sample() to get a random sample from a list

The sample() function is used to get a random sample of specified size from a sequence (like a list). It returns a new list containing the selected elements.

python
import random
fruits = ['apple', 'banana', 'cherry', 'grapes', 'elderberry']
sample_fruits = random.sample(fruits, 3)
print(sample_fruits)

How It Works:

  • fruits: A list containing different fruit names.
  • random.sample(fruits, 3): This selects a random sample of 3 elements from the fruits list. The number 3 specifies the size of the sample.
  • The sample is randomly selected, and the order of the elements in the resulting list does not follow the order of the original list.

Output

['banana', 'elderberry', 'cherry']

6. Using uniform() to generate a random floating-point number in a range

The uniform() function generates a random floating-point number within a specified range, where the number can be any value between the given lower and upper bounds (inclusive).

python
import random
random_number = random.uniform(10, 20)
print(random_number)

How It Works:

  • random.uniform(10, 20): This generates a random floating-point number between 10 and 20 (inclusive of both ends).
  • The resulting number can be any decimal value within the range, not just an integer.

Output

14.5679828311621

7. Using seed() to set the seed for the random number generator

The seed() function is used to initialize the random number generator with a specific seed value. This ensures that the sequence of random numbers generated is reproducible.

python
import random
random.seed(42)
print(random.random())

How It Works:

  • random.seed(42): This sets the seed of the random number generator to 42. With the same seed, the random number generator will produce the same sequence of numbers each time the code is run.
  • random.random(): This generates a random floating-point number between 0 and 1. Because the seed is fixed, it will always return the same value when the code is run with the same seed.

Output

0.6394267984578837

8. Using randrange() to generate a random number from a specified range

The randrange() function generates a random number from a specified range. You can specify the start, stop, and step values.

python
import random
random_number = random.randrange(1, 10, 2)
print(random_number)

How It Works:

  • random.randrange(1, 10, 2): This generates a random number starting from 1, up to but not including 10, in steps of 2. So the possible numbers are 1, 3, 5, 7, and 9.
  • The step argument allows you to control the increment between generated numbers.

Output

5

9. Using gauss() to generate a random number from a Gaussian distribution

The gauss() function generates a random number based on a Gaussian (normal) distribution. It takes two arguments: the mean and the standard deviation of the distribution.

python
import random
mean = 0
std_dev = 1
random_number = random.gauss(mean, std_dev)
print(random_number)

How It Works:

  • random.gauss(mean, std_dev): This generates a random number from a Gaussian distribution with the specified mean and standard deviation. In this example, the mean is 0 and the standard deviation is 1.
  • The number generated follows a bell curve centered around the mean. Most generated numbers will be close to the mean, but values can be more spread out depending on the standard deviation.

Output

0.3245316390222306

What's Next?

Up next: the datetime module. Working with dates and times is essential for many applications — from logging and scheduling to data analysis. In this next section, you'll learn how to handle, manipulate, and format dates and times effectively in Python.