Search code examples
pythonrandom

What does the random.sample() method in Python do?


I want to know the use of random.sample() method and what does it give? When should it be used and some example usage.


Solution

  • According to documentation:

    random.sample(population, k)

    Return a k length list of unique elements chosen from the population sequence. Used for random sampling without replacement.

    Basically, it picks k unique random elements, a sample, from a sequence:

    >>> import random
    >>> c = list(range(0, 15))
    >>> c
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
    >>> random.sample(c, 5)
    [9, 2, 3, 14, 11]
    

    random.sample works also directly from a range:

    >>> c = range(0, 15)
    >>> c
    range(0, 15)
    >>> random.sample(c, 5)
    [12, 3, 6, 14, 10]
    

    In versions earlier than 3.11, random.sample works with sets too:

    >>> c = {1, 2, 4}
    >>> random.sample(c, 2)
    [4, 1]
    

    However, random.sample doesn't work with arbitrary iterators:

    >>> c = [1, 3]
    >>> random.sample(iter(c), 5)
    TypeError: Population must be a sequence.  For dicts or sets, use sorted(d).
    

    In version 3.9, the counts parameter was added:

    Repeated elements can be specified one at a time or with the optional keyword-only counts parameter. For example, sample(['red', 'blue'], counts=[4, 2], k=5) is equivalent to sample(['red', 'red', 'red', 'red', 'blue', 'blue'], k=5).