diff --git a/Doc/library/random.rst b/Doc/library/random.rst index ad4a1ce7c31275..de553627f1b81e 100644 --- a/Doc/library/random.rst +++ b/Doc/library/random.rst @@ -224,7 +224,7 @@ Functions for sequences The optional parameter *random*. -.. function:: sample(population, k, *, counts=None) +.. function:: sample(population, k=None, *, counts=None) Return a *k* length list of unique elements chosen from the population sequence. Used for random sampling without replacement. @@ -238,6 +238,10 @@ Functions for sequences Members of the population need not be :term:`hashable` or unique. If the population contains repeats, then each occurrence is a possible selection in the sample. + The number of elements to sample is specified through the *k* parameter. If + omitted, it defaults to ``len(population)``, and the function returns a shuffled + copy of the sequence. + 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', @@ -258,6 +262,8 @@ Functions for sequences The *population* must be a sequence. Automatic conversion of sets to lists is no longer supported. + The *k* argument is now optional. + Discrete distributions ---------------------- diff --git a/Lib/random.py b/Lib/random.py index c70294ee0cbf08..25ad83af37de9c 100644 --- a/Lib/random.py +++ b/Lib/random.py @@ -349,7 +349,7 @@ def shuffle(self, x): j = randbelow(i + 1) x[i], x[j] = x[j], x[i] - def sample(self, population, k, *, counts=None): + def sample(self, population, k=None, *, counts=None): """Chooses k unique random elements from a population sequence. Returns a new list containing elements from the population while @@ -406,6 +406,8 @@ def sample(self, population, k, *, counts=None): raise TypeError("Population must be a sequence. " "For dicts or sets, use sorted(d).") n = len(population) + if k is None: + k = n if counts is not None: cum_counts = list(_accumulate(counts)) if len(cum_counts) != n: