Skip to content

Instantly share code, notes, and snippets.

@mdshw5
Last active August 29, 2015 13:55
Show Gist options
  • Save mdshw5/8774259 to your computer and use it in GitHub Desktop.
Save mdshw5/8774259 to your computer and use it in GitHub Desktop.
random.choice in Python 2.X vs 3.X
def choice(self, seq):
"""Choose a random element from a non-empty sequence."""
return seq[int(self.random() * len(seq))] # raises IndexError
def choice(self, seq):
"""Choose a random element from a non-empty sequence."""
try:
i = self._randbelow(len(seq))
except ValueError:
raise IndexError('Cannot choose from an empty sequence')
return seq[i]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment