"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Generate Unique Random Numbers within a Specific Range in Python?

How to Generate Unique Random Numbers within a Specific Range in Python?

Published on 2024-11-17
Browse:486

How to Generate Unique Random Numbers within a Specific Range in Python?

Generating Unique Random Numbers within a Range

When generating random numbers, ensuring that each number is unique can be a challenge. While it's possible to use conditional statements to check for duplicates, this approach becomes cumbersome when dealing with large ranges or large numbers.

One straightforward method for generating a list of unique random numbers is to use Python's random.sample() function. This function takes two arguments: a population (the range of numbers within which to generate the random numbers) and a sample size (the number of unique numbers to generate).

For example, to generate three unique random numbers within the range 1 to 100, you would use the following code:

import random
random_numbers = random.sample(range(1, 101), 3)

The random.sample() function will return a list of three unique random numbers from the specified range, such as:

[77, 52, 45]

This method is particularly useful when dealing with large ranges or large numbers of random numbers, as it avoids the need for complex conditional statements to check for duplicates. Additionally, the random.sample() function ensures a uniform distribution of the generated numbers, which is essential for many applications.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3