← Back to NumPy Course | Chapter 9: Random Module | Lesson 5 of 6

np.random.shuffle()

shuffle mixes up an array's order in place, like shuffling a deck of cards.

In this page:

  1. np.random.shuffle()
Syntax
python
np.random.shuffle(arr)    # in place

np.random.shuffle()

np.random.shuffle rearranges the elements of an array along its first axis, in place, and returns None. Use np.random.permutation to get a shuffled copy instead. For 2-D arrays only the rows move, not the values inside rows.

Note: permutation(10) gives a random ordering of 0 to 9, ideal for train/test splits.

Example: np.random.shuffle()

python
import numpy as np

np.random.seed(7)
a = np.arange(8)
np.random.shuffle(a)
print(a)
print(np.random.permutation(5))

# Output:
# [2 5 0 6 3 1 4 7]
# [3 4 2 1 0]
Related Topics
Common Mistakes
  1. Assigning the result of shuffle, which is None
  2. Expecting columns to shuffle too
  3. Shuffling when you needed a copy
Chapter Summary
  • shuffle changes the array in place
  • It returns None
  • permutation returns a copy
  • Only the first axis is shuffled
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.