Unlike shuffle(), which mutates its argument in place and returns nothing, permutation() always returns a brand-new shuffled array and leaves the original input completely unmodified — the safer, non-destructive counterpart to shuffle(). Passing an integer n is shorthand for shuffling a range of n integers, a common way to generate a random ordering of indices without first building the range array yourself.
1Understanding np.random.permutation()
Unlike shuffle(), which mutates its argument in place and returns nothing, permutation() always returns a brand-new shuffled array and leaves the original input completely unmodified — the safer, non-destructive counterpart to shuffle(). Passing an integer n is shorthand for shuffling a range of n integers, a common way to generate a random ordering of indices without first building the range array yourself.
Use permutation() instead of shuffle() specifically when you need to keep the original, unshuffled array around — shuffle() would destroy that original ordering permanently by mutating in place.
import numpy as np
np.random.seed(0)
arr = np.array([1, 2, 3, 4, 5])
shuffled = np.random.permutation(arr)
print(shuffled)
print(arr)2Practical Example
Here is a real-world application of np.random.permutation() showing how it is used in production NumPy code.
import numpy as np
np.random.seed(0)
indices = np.random.permutation(5)
print(indices)3Best Practices
Follow these guidelines when working with np.random.permutation():
1. Use permutation() over shuffle() whenever the original, unshuffled array needs to remain available afterward
2. Pass an integer directly to permutation() as a convenient shorthand for generating a random ordering of indices, instead of building the range array first
3. Use a permutation of indices to shuffle several related arrays in the same consistent random order, by applying the same generated index permutation to each one
Tip: Use permutation() instead of shuffle() specifically when you need to keep the original, unshuffled array around — shuffle() would destroy that original ordering permanently by mutating in place.
import numpy as np
np.random.seed(0)
arr = np.array([1, 2, 3, 4, 5])
shuffled = np.random.permutation(arr)
print(shuffled)
print(arr)