Generating a List of Unique Random Numbers

Write a Python program that uses the random module to generate a list of 5 unique random numbers between 0 and 30.

Example 1:

Input: None
Output: [6, 29, 10, 23, 8]  # Output may vary

Example 2:

Input: None
Output: [12, 28, 4, 15, 22]  # Output may vary

The random module contains a function sample(population, k) that returns a k length list of unique elements chosen from the population sequence.

import random

# Define the function
def generate_unique_random_numbers():
    return random.sample(range(31), 5)

# Test the function
print(generate_unique_random_numbers())  # Output may vary
print(generate_unique_random_numbers())  # Output may vary

© Let’s Data Science

LOGIN

Unlock AI & Data Science treasures. Log in!