Giving random.choice(seq) an empty sequence leads to a misleading error message, as per this example: >>> import random; random.choice([]) Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.3/random.py", line 231, in choice return seq[int(self.random() * len(seq))] IndexError: list index out of range A simple fix is to "assert len(seq) > 0" in the choice method.
Logged In: YES user_id=80475 Perhaps I've been using it for too long, but I do not find the error message to misleading. Also, I like having this method as simple and lightweight as possible though it may be worthwhile to add a line to the docs, "If the sequence is emtpy, raises a TypeError." If someone accepts this request, it should implemented as a try/except rather than an assertion. That approach would also let you catch TypeErrors raised is the argument doesn't define __len__ and __getitem__, for example: random.choice(set('abc'))
Logged In: YES user_id=31435 No, I don't want to change this either. choice() is one of the few library functions where speed matters a lot, and checking for invalid arguments *just* to give a wordier error message would be a losing tradeoff because of that. If you want to add a line to the docs, that's cool, but not "If the sequence is empty, raises TypeError". That's a bad idea because it actually raises IndexError .