Shuffling List with Fisher-Yates Algorithm

  • Share this:

Code introduction


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


Technology Stack : random

Code Type : Function

Code Difficulty : Intermediate


                
                    
import random

def shuffle_list(items):
    """
    Shuffle a list of items using the 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: