Fisher-Yates Shuffle Algorithm Implementation

  • Share this:

Code introduction


This function uses the Fisher-Yates shuffle algorithm to randomly shuffle the elements of the given list.


Technology Stack : random

Code Type : Function

Code Difficulty : Intermediate


                
                    
import random

def shuffle_list(input_list):
    """
    Shuffles a given list using the Fisher-Yates shuffle algorithm.
    """
    output_list = input_list[:]
    for i in range(len(output_list) - 1, 0, -1):
        j = random.randint(0, i)
        output_list[i], output_list[j] = output_list[j], output_list[i]
    return output_list                
              
Tags: