shuffle() mutates its argument directly and returns None — a common mistake is writing an assignment like `arr = np.random.shuffle(arr)`, which sets arr to None instead of the shuffled array, since shuffle() doesn't return anything to reassign. For a multi-dimensional array, shuffle() only reorders along the first axis, shuffling entire rows relative to each other rather than shuffling every individual element throughout the array.
1Understanding np.random.shuffle()
shuffle() mutates its argument directly and returns None — a common mistake is writing an assignment like arr = np.random.shuffle(arr), which sets arr to None instead of the shuffled array, since shuffle() doesn't return anything to reassign. For a multi-dimensional array, shuffle() only reorders along the first axis, shuffling entire rows relative to each other rather than shuffling every individual element throughout the array.
Never write `arr = np.random.shuffle(arr)` — shuffle() modifies the array in place and returns None, so that assignment overwrites arr with None; just call np.random.shuffle(arr) on its own line.
import numpy as np
np.random.seed(0)
arr = np.array([1, 2, 3, 4, 5])
np.random.shuffle(arr)
print(arr)2Practical Example
Here is a real-world application of np.random.shuffle() showing how it is used in production NumPy code.
import numpy as np
np.random.seed(0)
matrix = np.array([[1, 2], [3, 4], [5, 6]])
np.random.shuffle(matrix)
print(matrix)3Best Practices
Follow these guidelines when working with np.random.shuffle():
1. Call shuffle() as a standalone statement, not as the right-hand side of an assignment, since it returns None
2. Use np.random.permutation() instead of shuffle() when you need a shuffled copy and want to leave the original array untouched
3. Remember shuffle() on a multi-dimensional array only reorders along the first axis, whole rows, not every individual element
Tip: Never write `arr = np.random.shuffle(arr)` — shuffle() modifies the array in place and returns None, so that assignment overwrites arr with None; just call np.random.shuffle(arr) on its own line.
import numpy as np
np.random.seed(0)
arr = np.array([1, 2, 3, 4, 5])
np.random.shuffle(arr)
print(arr)