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)
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!