Thursday, September 5, 2013

random failure

>>> random.choice({0:1, 2:3})
>>> random.choice({0:1, 2:3})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python27\lib\", line 274, in choice
    return seq[int(self.random() * len(seq))]  # raises IndexError if seq is empty 
KeyError: 1

Alright pythonauts, why does this fail sometimes and succeed others? :-)


  1. Some pydestrians might learn from the answer :)

  2. Because random.choice expects something that can be indexed by elements of range of its len. So range of len contains 0 and 1, 0th item is 1, but 1st item doesn't exist. Half the time it gives 1, other half it KeyErrors.