HOWTO · NumPy

numpy.random.permutation() Function in NumPy

The numpy.random.permutation() function returns a randomly permuted copy of an array, or a permuted range of integers when given an integer, and leaves the original data unchanged — unlike numpy.random.shuffle(), which shuffles the array in place.

On this page

numpy.random.permutation() randomly permutes a sequence, or returns a permuted range. Pass it an array and it returns a shuffled copy of that array — the original is left exactly as it was. Pass it an integer n and it returns the integers from 0 to n - 1 in a random order. That copy-instead-of-modify behavior is the whole difference from numpy.random.shuffle(), which shuffles an array in place.

Permute an Array Without Changing the Original

With an array, permutation() builds a new array holding the same elements in a random order:

import numpy as np

original_array = np.array([1, 2, 3, 4, 5])
shuffled_array = np.random.permutation(original_array)

print("Original Array:", original_array)
print("Shuffled Array:", shuffled_array)

Output:

Original Array: [1 2 3 4 5]
Shuffled Array: [3 1 5 2 4]

The order in shuffled_array is random, so the output above is one possible result, not what every run produces. What does not vary is original_array: it still holds [1 2 3 4 5], which is what makes permutation() the right choice when the original order still matters later — for example, when a dataset must stay aligned with its labels.

With an integer, permutation() returns a permuted range, which is a convenient way to get random indices:

import numpy as np

n = 5
permuted_indices = np.random.permutation(n)

print("Permuted Indices:", permuted_indices)

Output:

Permuted Indices: [4 0 2 3 1]

Again, the exact order differs from run to run. Passing an integer is equivalent to building the range first with np.arange(n) and permuting that array.

Compare permutation() and shuffle()

The two functions differ in what they hand back and what they do to your data. permutation() returns a new array and never touches its input. numpy.random.shuffle() returns nothing and reorders the array itself, in place:

import numpy as np

original_array = np.array([1, 2, 3, 4, 5])
np.random.shuffle(original_array)

print("Shuffled Original Array:", original_array)

Output:

Shuffled Original Array: [2 5 1 4 3]

After this call, the original order is gone. Choose shuffle() when you do not need it and want to reorder in place; choose permutation() when the original must survive. One practical consequence of the copy: on a large dataset, permutation() needs memory for the second array, so weigh that convenience against the extra memory when the data is big.