How To Create A Random List With Only Unique Values?
I want to create a random list with 100 elements. So far, so good... Example 1: works fine, because the function has a range which is big enough not to repeat any value list = rand
Solution 1:
In this case, do not use random.sample
, but build the list from elements chosen within a range:
import random
[random.randrange(50, 80) for _ in range(100)]
example output:
[57,
52,
59,
67,
52, # some elements repeat
64,
75,
...
Solution 2:
Solution 3:
Solution 4:
Use list comprehension
+ randint
,
[random.randint(1,200) for _ in range(100)]
See the element are repeating the count is not 100
,
In [6]: len(set([random.randint(1,200) for _ in range(100)]))
Out[6]: 76
Post a Comment for "How To Create A Random List With Only Unique Values?"