diff -r 92842e347d98 Lib/random.py --- a/Lib/random.py Thu Sep 08 00:56:17 2011 +0200 +++ b/Lib/random.py Fri Sep 09 02:07:41 2011 +0200 @@ -46,7 +46,7 @@ from hashlib import sha512 as _sha512 __all__ = ["Random","seed","random","uniform","randint","choice","sample", - "randrange","shuffle","normalvariate","lognormvariate", + "pop","randrange","shuffle","normalvariate","lognormvariate", "expovariate","vonmisesvariate","gammavariate","triangular", "gauss","betavariate","paretovariate","weibullvariate", "getstate","setstate", "getrandbits", @@ -252,6 +252,14 @@ raise IndexError('Cannot choose from an empty sequence') return seq[i] + def pop(self, seq): + """Remove and return 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.pop(i) + def shuffle(self, x, random=None, int=int): """x, random=random.random -> shuffle list x in place; return None. @@ -709,6 +717,7 @@ triangular = _inst.triangular randint = _inst.randint choice = _inst.choice +pop = _inst.pop randrange = _inst.randrange sample = _inst.sample shuffle = _inst.shuffle diff -r 92842e347d98 Lib/test/test_random.py --- a/Lib/test/test_random.py Thu Sep 08 00:56:17 2011 +0200 +++ b/Lib/test/test_random.py Fri Sep 09 02:07:41 2011 +0200 @@ -49,6 +49,13 @@ self.assertEqual(choice([50]), 50) self.assertIn(choice([25, 75]), [25, 75]) + def test_pop(self): + pop = self.gen.pop + with self.assertRaises(IndexError): + pop([]) + self.assertEqual(pop([50]), 50) + self.assertIn(pop([25, 75]), [25, 75]) + def test_sample(self): # For the entire allowable range of 0 <= k <= N, validate that # the sample is of the correct length and contains only unique items