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

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

Susan Sarandon
Release: 2024-12-08 07:03:10
Original
789 people have browsed it

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

Random Number Generation with Unique Values

When creating a list of random numbers, it's undesirable to have duplicates. Fortunately, there is an elegant solution using the random module, as illustrated in the following query.

Query: Duplicates in Random Number List

"_I generated random integers using random.randint(0, 100), but some numbers were duplicated. Is there a way to create a list of unique random numbers?"_

Response: Utilizing random.sample()

The secret lies in random.sample(). It selects elements from a given population while ensuring uniqueness. Consider the following code snippet:

import random
random.sample(range(100), 10)
Copy after login

This expression returns a list of 10 unique numbers ranging from 0 to 99. The range() function generates a sequence of integers, and random.sample() randomly selects 10 elements from this sequence without repetition.

The above is the detailed content of How Can I Generate a List of Unique Random Numbers 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