Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion Doc/library/random.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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',
Expand All @@ -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
----------------------

Expand Down
4 changes: 3 additions & 1 deletion Lib/random.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down