# Understand numpy.random.permutation(): Randomly permute a sequence – Numpy Tutorial

By | September 22, 2019

numpy.random.permutation() can return a sequence randomly, which is very helpful in random two or more sequences. In this tutorial, we will introduce how to use this function correctly.

## Syntax

numpy.random.permutation(x)

## Parameter

x : int or array_like, if x is a integer, this function will return the random sequence of range(x)

## Return

A random sequence

Here are some examples on how to use this function.

## x is a integer

import numpy as np

x = 5

seq = np.random.permutation(5)
print(seq)

The random sequence is:

[3 4 2 0 1]

it is created based on range(5).

## x is an array

import numpy as np

#create a 3 * 3 matrix
x = np.array(range(9)).reshape(3,3)
print(x)

seq = np.random.permutation(x)
print(seq)

The sequence is:

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

The random sequence is:

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

From the result we will find, numpy.random.permutation() will randomly permute a sequence by its first aixs.

## Permute two sequences by the same random order

This is very helpful when you are generating random data, the example code is:

Create two sequeces with the same shape

import numpy as np

x1 = np.array(range(9))
print(x1)
x2 = x1+3
print(x2)

The x1 and x2 is:

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

Create a random order sequence

inx = np.random.permutation(9)

Get the same random sequences

random_x1 = x1[inx]
random_x2 = x2[inx]
print(random_x1)
print(random_x2)

The random sequences are:

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

From the result we will find, the random order of  random_x1 and random_x2 is the same.