NumPy Tutorial NumPy Statistics NumPy References

NumPy - random.shuffle() function



The NumPy random.shuffle() function modify a sequence in-place by shuffling its contents. This function only shuffles the array along the first axis of a multi-dimensional array.

Syntax

numpy.random.shuffle(x)

Parameters

x Required. Specify the array or list to be shuffled.

Return Value

None.

Example:

In the example below, random.shuffle() function is used to shuffle the content of a given list.

import numpy as np

x = np.arange(0, 10)

#before shuffling, x contains:
print("x contains:", x)

#shuffle the content of x
np.random.shuffle(x)

#after shuffling, x contains:
print("x contains:", x)

The output of the above code will be:

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

Example:

When the function is used with a multi-dimensional array, it shuffles the content only along first axis.

import numpy as np

x = np.arange(1, 10).reshape(3,3)

#before shuffling, x contains:
print("x contains:")
print(x)

#shuffle the content of x
np.random.shuffle(x)

#after shuffling, x contains:
print("\nx contains:")
print(x)

The output of the above code will be:

x contains:
[[1 2 3]
 [4 5 6]
 [7 8 9]]
 
x contains:
[[7 8 9]
 [1 2 3]
 [4 5 6]]

❮ NumPy - Random

5