Fix corner case for Random.choice() and add tests.

This commit is contained in:
Raymond Hettinger 2010-09-07 10:06:56 +00:00
parent c324697bac
commit dc4872eefe
2 changed files with 12 additions and 1 deletions

View file

@ -239,7 +239,11 @@ class Random(_random.Random):
def choice(self, seq):
"""Choose a random element from a non-empty sequence."""
return seq[self._randbelow(len(seq))] # raises IndexError if seq is empty
try:
i = self._randbelow(len(seq))
except ValueError:
raise IndexError('Cannot choose from an empty sequence')
return seq[i]
def shuffle(self, x, random=None, int=int):
"""x, random=random.random -> shuffle list x in place; return None.