diff -r f9391e2b74a5 Doc/library/random.rst --- a/Doc/library/random.rst Fri Feb 19 08:57:50 2016 +0100 +++ b/Doc/library/random.rst Fri Feb 19 21:25:24 2016 +0200 @@ -132,6 +132,13 @@ that most permutations of a long sequence can never be generated. +.. function:: shuffled(x) + + Return new Shuffled list of the given sequence x leaving the original list unchanged. + + .. versionadded:: 3.6 + + .. function:: sample(population, k) Return a *k* length list of unique elements chosen from the population sequence diff -r f9391e2b74a5 Lib/random.py --- a/Lib/random.py Fri Feb 19 08:57:50 2016 +0100 +++ b/Lib/random.py Fri Feb 19 21:25:24 2016 +0200 @@ -49,7 +49,7 @@ "expovariate","vonmisesvariate","gammavariate","triangular", "gauss","betavariate","paretovariate","weibullvariate", "getstate","setstate", "getrandbits", - "SystemRandom"] + "SystemRandom","shuffled"] NV_MAGICCONST = 4 * _exp(-0.5)/_sqrt(2.0) TWOPI = 2.0*_pi @@ -335,6 +335,10 @@ result[i] = population[j] return result + def shuffled(self, x): + """Return new Shuffled list of the given list x leaving the original list unchanged""" + return self.sample(x, len(x)) + ## -------------------- real-valued distributions ------------------- ## -------------------- uniform distribution ------------------- diff -r f9391e2b74a5 Lib/test/test_random.py --- a/Lib/test/test_random.py Fri Feb 19 08:57:50 2016 +0100 +++ b/Lib/test/test_random.py Fri Feb 19 21:25:24 2016 +0200 @@ -141,6 +141,20 @@ def test_sample_on_dicts(self): self.assertRaises(TypeError, self.gen.sample, dict.fromkeys('abcdef'), 2) + def test_shuffled(self): + shuffled = self.gen.shuffled + self.assertEqual(shuffled([]), []) + self.assertEqual(shuffled([37]), [37]) + for seq in [list(range(n)) for n in range(10)]: + shuffled_seq = shuffled(seq) + self.assertEqual(len(seq), len(shuffled_seq)) + self.assertEqual(set(seq), set(shuffled_seq)) + lst = list(range(1000)) + shuffled_lst = shuffled(lst) + self.assertTrue(lst != shuffled_lst) + # test that the original list is not changec + self.assertEqual(lst, list(range(1000))) + def test_gauss(self): # Ensure that the seed() method initializes all the hidden state. In # particular, through 2.2.1 it failed to reset a piece of state used