Random Permutations

🔀 NumPy Random Permutations

Random permutation means randomly shuffling the elements of an array, either in-place or by creating a shuffled copy.
NumPy provides efficient methods for this.

All functions are in numpy.random.


 1. shuffle() — Shuffle Array In-Place

Shuffles the elements without creating a new array.


 

Output (example):

[3 5 1 4 2]

💡 Original array arr is modified.


 2. permutation() — Return Shuffled Copy

Creates a new array and leaves the original unchanged.


Output (example):

Original: [1 2 3 4 5]
Shuffled: [4 1 5 3 2]

 3. Permute 2D Arrays

  • shuffle() → shuffles rows only

  • permutation() → can shuffle rows or 1D flattened array


 


 4. Seed for Reproducibility

To get the same permutation every time:



 5. Random Index Permutation

Sometimes you just need shuffled indices:



🔄 Summary Table

Function Modifies Original? Returns New Array Notes
shuffle() ✅ Yes ❌ No In-place shuffling
permutation() ❌ No ✅ Yes Returns shuffled copy
random.permutation(n) ❌ No ✅ Yes Generates shuffled numbers from 0 to n-1

🎯 Practice Tasks

  1. Shuffle a 1D array of 20 elements.

  2. Shuffle rows of a 2D array 4×3.

  3. Use permutation() to randomly reorder [10, 20, 30, 40, 50] without changing original array.

  4. Generate a random index permutation and use it to shuffle an array.

You may also like...