Skip to content

Commit ff2db57

Browse files
committed
gh-130285: Support zero counts in random.sample()
1 parent e1e8520 commit ff2db57

File tree

1 file changed

+6
-3
lines changed

1 file changed

+6
-3
lines changed

Lib/random.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -421,11 +421,14 @@ def sample(self, population, k, *, counts=None):
421421
cum_counts = list(_accumulate(counts))
422422
if len(cum_counts) != n:
423423
raise ValueError('The number of counts does not match the population')
424-
total = cum_counts.pop()
424+
try:
425+
total = cum_counts.pop()
426+
except IndexError:
427+
total = 0
425428
if not isinstance(total, int):
426429
raise TypeError('Counts must be integers')
427-
if total <= 0:
428-
raise ValueError('Total of counts must be greater than zero')
430+
if total < 0:
431+
raise ValueError('Total of counts must be non-negative')
429432
selections = self.sample(range(total), k=k)
430433
bisect = _bisect
431434
return [population[bisect(cum_counts, s)] for s in selections]

0 commit comments

Comments
 (0)