Home > Backend Development > Python Tutorial > How Can I Generate a List of Unique Random Numbers Within a Range in Python?

How Can I Generate a List of Unique Random Numbers Within a Range in Python?

Susan Sarandon
Release: 2024-12-02 22:39:11
Original
759 people have browsed it

How Can I Generate a List of Unique Random Numbers Within a Range in Python?

Unique Random Number Generation Within a Range

Given the ability to generate a random number within a range using random.randint, the task arises of generating a list of unique random numbers. While iterative conditional statements may serve as a solution, a more elegant approach exists for efficiently achieving this outcome.

Random Sampling

Python's random module provides a function named sample specifically designed for sampling without replacement. This function takes a population (e.g., a list of numbers) and a sample size as arguments and returns a list of randomly selected unique elements from the population.

For example, to generate a list of 3 unique random numbers within the range [1, 100], one can use the following code:

import random

population = range(1, 100)  # Initialize the population
sample_size = 3  # Set the sample size
random_sample = random.sample(population, sample_size)
Copy after login

random_sample will now contain a list of 3 unique random numbers within the specified range.

Handling Size Discrepancies

It is important to note that if the sample size exceeds the population size, sample will raise a ValueError. To handle this scenario, one can use a try-except block to catch the exception and handle it accordingly.

For instance, to attempt generating a sample of size 3 from a population of size 2, one can write the following code:

try:
    random.sample(range(1, 2), 3)
except ValueError:
    print('Sample size exceeded population size.')
Copy after login

If the sample size is larger than the population size, this code will print an informative message rather than crashing.

The above is the detailed content of How Can I Generate a List of Unique Random Numbers Within a Range in Python?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template