How to use Fisher-Yates Shuffle Algorithm to shuffle an array In Python

This is the one of the most efficient methods, it is the Fisher–Yates shuffle Algorithm. Below program will help you understand this algorithm.

Python3




# Import required module
import random
import numpy as np
 
 
# A function to generate a random
# permutation of array
def shuffler (arr, n):
     
    # We will Start from the last element
    # and swap one by one.
    for i in range(n-1,0,-1):
         
        # Pick a random index from 0 to i
        j = random.randint(0,i+1)
         
        # Swap arr[i] with the element at random index
        arr[i],arr[j] = arr[j],arr[i]
    return arr
 
   
   
# Driver code
     
# Assign array
arr = np.array([1, 2, 3, 4, 5, 6])
 
# Display original array
print("Original array: ",arr)
 
# Get length of array
n = len(arr)
 
# Use shuffler() function to get shuffled array
print("Shuffled array: ",shuffler(arr, n))


Output:

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

Shuffle an array in Python

Shuffling a sequence of numbers have always been a useful utility, it is nothing but rearranging the elements in an array. Knowing more than one method to achieve this can always be a plus. Let’s discuss certain ways in which this can be achieved.

Similar Reads

Using shuffle() method from numpy library

Here we are using the shuffle() method from numpy library to shuffle an array in Python....

Using shuffle() method from Random library to shuffle the given array.

...

Using sample() method to shuffle an array

Here we are using shuffle method from the built-in random module to shuffle the entire array at once....

Selecting random indices and swapping them

...

Using Fisher-Yates Shuffle Algorithm to shuffle an array

Here we are using the sample method from the random library to shuffle an array....

Selecting random indices and storing in a new list

...