OneBite.Dev - Coding blog in a bite size

shuffle the elements in an array in python

Code snippet on how to shuffle the elements in an array in python

import random 
  
# function to shuffle the list 
def shuffle_list(list): 
    # shuffle the list 
    random.shuffle(list) 
    return list 
  
list = [3, 6, 7, 8] 
print(shuffle_list(list)) 

This code uses Python’s random library to generate a random sequence of numbers that are then used to rearrange the elements in a provided list. The shuffle_list function is declared and passed the list variable as an argument. Inside the function, the list is shuffled using the random.shuffle() method and then returned. Lastly, the shuffled list is printed.

python