-
-
Notifications
You must be signed in to change notification settings - Fork 31.2k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
random.sample raises "IndexError: pop from empty list" when both "population" and "counts" are empty #130285
Comments
Neither of these cases was tested or intended behavior, so it would be reasonable to fix them both. I'll work on a PR soonish. Thanks for the report. Because of the possibility of breaking code, I'm -0 on backporting the edit. |
Somewhat related is the situation when >>> random.sample('abc', k=0, counts=[0,0,0])
Traceback (most recent call last):
File "<python-input-1>", line 1, in <module>
random.sample('abc', k=0, counts=[0,0,0])
~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/path/to/lib/python3.14/random.py", line 428, in sample
raise ValueError('Total of counts must be greater than zero')
ValueError: Total of counts must be greater than zero According to the docs:
So, extrapolating this to zero counts, this would be |
I propose we do Line 421 in 8207454
Line 422 in 8207454
And add tests, what do you think @rhettinger ? I see you are planning to do this |
What about (random.py#L424) total = cum_counts.pop() if cum_counts else 0
if not isinstance(total, int):
raise TypeError('Counts must be integers')
if total < 0:
raise ValueError('Total of counts must be non-negative') That would also address the If |
…e() (pythongh-130291) (cherry picked from commit 286c517) Co-authored-by: Raymond Hettinger <[email protected]>
…e() (pythongh-130291) (cherry picked from commit 286c517) Co-authored-by: Raymond Hettinger <[email protected]>
Bug report
Bug description:
I just encountered the situation where I used
random.sample
but both thepopulation
andcounts
arguments were empty (my algorithm had nothing left to choose from). So, basically this situation:Instead of the
IndexError
, I expected aValueError
, similar to the following situations:The docs mention that
In addition, I would expect the following to work:
similar to how it works when
counts
is not specified:Not sure though what CPython's backwards-compatibility policy has to say here, since changing the exception type – or, in the second case, removing the exception altogether – might actually break someone's code...
Tested with:
CPython versions tested on:
3.14
Operating systems tested on:
Linux
Linked PRs
The text was updated successfully, but these errors were encountered: