Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork33.7k
Description
Bug report
Bug description:
I just encountered the situation where I usedrandom.sample but both thepopulation andcounts arguments were empty (my algorithm had nothing left to choose from). So, basically this situation:
>>>random.sample([],1,counts=[])Traceback (mostrecentcalllast):File"<python-input-1>",line1,in<module>random.sample([],1,counts=[])~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^File"/path/to/lib/python3.14/random.py",line424,insampletotal=cum_counts.pop()IndexError:popfromemptylist
Instead of theIndexError, I expected aValueError, similar to the following situations:
>>>random.sample([],1)Traceback (mostrecentcalllast):File"<python-input-2>",line1,in<module>random.sample([],1)~~~~~~~~~~~~~^^^^^^^File"/path/to/lib/python3.14/random.py",line434,insampleraiseValueError("Sample larger than population or is negative")ValueError:Samplelargerthanpopulationorisnegative>>>>>>random.sample([1],2,counts=[1])Traceback (mostrecentcalllast):File"<python-input-3>",line1,in<module>random.sample([1],2,counts=[1])~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^File"/path/to/lib/python3.14/random.py",line429,insampleselections=self.sample(range(total),k=k)File"/path/to/lib/python3.14/random.py",line434,insampleraiseValueError("Sample larger than population or is negative")ValueError:Samplelargerthanpopulationorisnegative
The docs mention that
If the sample size is larger than the population size, aValueError is raised.
In addition, I would expect the following to work:
>>>random.sample([],0,counts=[])Traceback (mostrecentcalllast):File"<python-input-4>",line1,in<module>random.sample([],0,counts=[])~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^File"/path/to/lib/python3.14/random.py",line424,insampletotal=cum_counts.pop()IndexError:popfromemptylist
similar to how it works whencounts is not specified:
>>>random.sample([],0)[]
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:
Python 3.14.0a5 (main, Feb 12 2025, 14:51:40) [Clang 19.1.6 ] on linuxcpython-3.14.0a5-linux-x86_64-gnuCPython versions tested on:
3.14
Operating systems tested on:
Linux