Latest Code Tutorials

np.random.permutation: How to Generate Random Permutation

To generate random Permutation in Python, then you can use the np random permutation. If the provided parameter is a multi-dimensional array, it is only shuffled along with its first index. If the parameter is an integer, randomly permute np.


The np.random.permutation() is a mathematical function randomly permutes a sequence or returns a permuted range. The random permutation() method accepts x, an int or array_like parameter, and returns the permuted sequence or array range.




x: int or array_like
If x is the integer value, it randomly permutes np.arange(x).

If x is the array, make a copy and shuffle the elements randomly.

Return Value

The np.random.permutation() function returns permuted sequence or array range.

Steps to Generate Random Permutation In NumPy

Step 1: Import NumPy library

I am using Python 3.8, which is the latest at the time of this tutorial.

If you have not installed the NumPy library in your machine, then you can install it using the following command. 

python3 -m pip install -U numpy

In the past, if you have used packages like Pandas, then chances are you have already installed NumPy.

Now, let’s move ahead and create a project file called and inside that file, import NumPy library.


import numpy as np

Step 2: Define np.random.permutation function

Python np.random.permutation() function takes an argument. Let’s pass the integer 10 as an argument.

That means it will output 10 items randomly generated in the NumPy array.

See the following code.


import numpy as np

data = np.random.permutation(10)


[5 8 7 3 4 6 1 9 0 2]

Pass array as an argument to the np.random.permutation()

In the above example, we have passed a digit(integer) in the argument.

Let’s pass an array of integers in the argument and see the output.


import numpy as np

data = np.random.permutation([11, 46, 29, 21, 19])


[11 21 29 19 46]

It reshuffles the list and gives the output.

Pass matrix as an argument to the np.random.permutation()

Numpy.arange() is a built-in numpy function that returns the ndarray object containing evenly spaced values within a defined interval. For example, if you want to create values from 1 to 10, you can use numpy.arange() function.

Now, we will use the arange() function to create values and then reshape it to the matrix and then pass the matrix to the np.random.permutation() function.

See the following code.


import numpy as np

arr = np.arange(9).reshape((3, 3))


➜  pyt python3
[[6 7 8]
 [0 1 2]
 [3 4 5]]
➜  pyt python3
[[0 1 2]
 [3 4 5]
 [6 7 8]]

Each time you run the above code, you will get different random output.

That is it for np.random.permutation() example.

See also

Numpy ceil()

Numpy floor()

Numpy index

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.