Home > Article > Backend Development > How to avoid duplication of random elements in python
Python can avoid duplication of random elements by using the sample() function of the random module, which returns a new list that stores random non-repeating elements.
Function usage example: (Recommended learning: Python video tutorial)
range() range can only be integers
random.sample(population, k)
Returns a k-length list of unique elements selected from the overall sequence or collection (potution) (list). The new list stores random non-repeating elements. Used for random sampling without replacement.
import random list = [1, 2, 3] print(random.sample(list ,2)) list = ["china","python","sky"] print(random.sample(list ,2)) list = range(1, 10000) print(random.sample(list ,5)) 输出: [1, 2] ['python', 'sky'] [6912, 1869, 5991, 721, 3388]
For more Python-related technical articles, please visit the Python Tutorial column to learn!
The above is the detailed content of How to avoid duplication of random elements in python. For more information, please follow other related articles on the PHP Chinese website!