Python | Ways to shuffle the list

Python Methods and Functions

Method # 1:

# Python3 demo code
# shuffle the list
# using the Fisher-Yates algorithm

 

import random

 
# initializing list

test_list = [ 1 , 4 , 5 , 6 3 ]

 
# Print original list

print ( "The original list is:" + str (test_list))

 
# using Fisher's algorithm - Yates
# shuffle the list

for i in range ( len (test_list) - 1 , 0 , - 1 ):

 

# Pick a random index from 0 to i

j = random.randint ( 0 , i + 1

 

# Swap arr [i] with a randomly indexed element

test_list [i], test_list [j] = test_list [j], test_list [i] 

 
# Print a shuffled list

< code class = "keyword"> print ( "The shuffled list is:" +   str (test_list))

Exit :

 The original list is: [1, 4, 5, 6, 3] The shuffled list is: [4, 3, 1, 5, 6] 

Method # 2: Using random.shuffle ()
This is the most recommended method shuffling list. Python provides this built-in function in its random library that shuffles the list in place. The downside to this is that the ordering of the list is lost in the process. Useful for developers looking to save time and fuss.

# Python3 demo code
# shuffle the list
# using random.shuffle ()

 

import random

 
# initializing list

test_list = [ 1 , 4 , 5 , 6 , 3 ]

  
# Print original list

print ( "The original list is:" + str (test_list))

 
# using random.shuffle ()
# shuffle the list
random.shuffle ( test_list)

 
# Print a shuffled list

print ( "The shuffled list is:" +   str (test_list))

Exit:

 The original list is: [1, 4, 5, 6, 3] T he shuffled list is: [5, 6, 4, 3, 1] 

Method # 3: Using random.sample ()
This is a pretty useful feature, better than the shuffle method used above in that it creates a new shuffled list and returns it rather than reordering the original list. This is useful when we need to keep the original list.

# Python3 demo code
# shuffle the list
# using random.sample ()

  

import random

  
# initializing list

test_list = [ 1 , 4 , 5 , 6 , 3 ]

  
# Print original list

print ( "The original list is:" + str (test_list))

 
# using random.sample ()
# shuffle the list

res = random.sample (test_list, len (test_list))

 
# Print a shuffled list

print ( " The shuffled list is: " +   str < code class = "plain"> (res))

Output:

 The original list is: [1, 4, 5, 6, 3] The shuffled list is: [5, 3, 6, 1, 4]