In-Place List Shuffling with Fisher-Yates Algorithm

  • Share this:

Code introduction


This function accepts a list as an argument and shuffles the elements of the list in place using the Fisher-Yates algorithm.


Technology Stack : random

Code Type : List shuffling function

Code Difficulty : Intermediate


                
                    
import random

def shuffle_list(items):
    """
    Shuffle the list in-place using Fisher-Yates algorithm.
    """
    for i in range(len(items) - 1, 0, -1):
        j = random.randint(0, i)
        items[i], items[j] = items[j], items[i]
    return items                
              
Tags: