[New-bugs-announce] [issue43097] IndexError msg of random.choice() not helpful

wyz23x2 report at bugs.python.org
Mon Feb 1 23:07:52 EST 2021


New submission from wyz23x2 <wyz23x2 at 163.com>:

When you apply `random.choice` on empty sequences:
>>> import random
>>> random.choice([])
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
    return seq[self._randbelow(len(seq))]
IndexError: list index out of range
This message doesn't clearly state the real problem -- an empty seq.
Meanwhile, many other methods give messages.
>>> [].pop()
Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
IndexError: pop from empty list
>>> import collections
>>> collections.deque().popleft()
Traceback (most recent call last):
  File "<stdin>", line 5, in <module>
IndexError: pop from an empty deque
>>> random.randrange(0, 0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Program Files\Python39\lib\random.py", line 316, in randrange
    raise ValueError("empty range for randrange() (%d, %d, %d)" % (istart, istop, width))
ValueError: empty range for randrange() (0, 0, 0)

P.S. Both are empty sequences/ranges, randrange() raises ValueError, while choice() raises IndexError.

----------
components: Library (Lib)
messages: 386128
nosy: wyz23x2
priority: normal
severity: normal
status: open
title: IndexError msg of random.choice() not helpful
versions: Python 3.10, Python 3.9

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue43097>
_______________________________________


More information about the New-bugs-announce mailing list