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

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

DDD
Release: 2024-12-05 11:37:11
Original
831 people have browsed it

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)
Copy after login

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

[77, 52, 45]
Copy after login

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.

The above is the detailed content of How to Generate Unique Random Numbers within a Specific 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template