Shuffling List Elements Function

  • Share this:

Code introduction


Defined a function to shuffle the elements in a list.


Technology Stack : random

Code Type : Function

Code Difficulty : Intermediate


                
                    
import random

def shuffle_list(items):
    if not isinstance(items, list):
        raise TypeError("items must be a list")
    shuffled_items = items[:]
    for i in range(len(shuffled_items) - 1, 0, -1):
        j = random.randint(0, i)
        shuffled_items[i], shuffled_items[j] = shuffled_items[j], shuffled_items[i]
    return shuffled_items                
              
Tags: