The shuffle() is an inbuilt method of the random module. It is used to shuffle a sequence (list). Shuffling a list of objects means changing the position of the elements of the sequence using Python.
Syntax of random.shuffle()
The order of the items in a sequence, such as a list, is rearranged using the shuffle() method. This function modifies the initial list rather than returning a new one.
Syntax: random.shuffle(sequence, function)
Parameters:
- sequence : can be a list
- function : optional and by default is random(). It should return a value between 0 and 1.
Returns: nothing
Python random.shuffle() function to shuffle list
Example 1:
Python3
import random
sample_list = [ 'A' , 'B' , 'C' , 'D' , 'E' ]
print ( "Original list : " )
print (sample_list)
random.shuffle(sample_list)
print ( "\nAfter the first shuffle : " )
print (sample_list)
random.shuffle(sample_list)
print ( "\nAfter the second shuffle : " )
print (sample_list)
|
Output :
Original list :
['A', 'B', 'C', 'D', 'E']
After the first shuffle :
['A', 'B', 'E', 'C', 'D']
After the second shuffle :
['C', 'E', 'B', 'D', 'A']
The shuffle() method cannot be used to shuffle immutable DataTypes like strings.
Example 2:
Python3
import random
def sample_function():
return 0.5
sample_list = [ 'A' , 'B' , 'C' , 'D' , 'E' ]
print ( "Original list : " )
print (sample_list)
random.shuffle(sample_list, sample_function)
print ( "\nAfter the first shuffle : " )
print (sample_list)
sample_list = [ 'A' , 'B' , 'C' , 'D' , 'E' ]
random.shuffle(sample_list, sample_function)
print ( "\nAfter the second shuffle : " )
print (sample_list)
|
Output :
Original list :
['A', 'B', 'C', 'D', 'E']
After the first shuffle :
['A', 'D', 'B', 'E', 'C']
After the second shuffle :
['A', 'D', 'B', 'E', 'C']