Home > Backend Development > Python Tutorial > How to Generate Unique Random Numbers Within a Range in Python?

How to Generate Unique Random Numbers Within a Range in Python?

Patricia Arquette
Release: 2024-11-26 10:13:09
Original
266 people have browsed it

How to Generate Unique Random Numbers Within a Range in Python?

Generating Unique Random Numbers Within a Range

Generating a random number within a range in Python using random.randint() is a common task, as is creating a list of n such numbers. However, when each number in the list must be unique, a more sophisticated approach is required.

While using conditional statements to check for duplicates is an option, a simpler and more efficient solution exists. The random.sample() function can be employed to perform sampling without replacement. This function takes a population and a sample size k, and returns k random and unique members of the population.

import random

population = range(1, 100)
unique_random_numbers = random.sample(population, 3)
print(unique_random_numbers)  # Output: [77, 52, 45]
Copy after login

If k exceeds the length of the population, a ValueError will be raised. To handle this case gracefully, you can catch the exception and handle it appropriately.

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

By using random.sample(), you can effortlessly generate a set of unique random numbers within a specified range, eliminating the need for complex conditional checks.

The above is the detailed content of How to Generate 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