random.shuffle() function in Python

sample() is an inbuilt method of the random module. It is used to shuffle a sequence (list). Shuffling means changing the position of the elements of the sequence. Here, the shuffling operation is inplace.

random.shuffle()

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

Example 1 : Shuffling a list



filter_none

edit
close

play_arrow

link
brightness_4
code

# import the random module
import random
  
  
# declare a list
sample_list = ['A', 'B', 'C', 'D', 'E']
  
print("Original list : ")
print(sample_list)
  
# first shuffle 
random.shuffle(sample_list)
print("\nAfter the first shuffle : ")
print(sample_list)
  
# second shuffle
random.shuffle(sample_list)
print("\nAfter the second shuffle : ")
print(sample_list)

chevron_right


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:

filter_none

edit
close

play_arrow

link
brightness_4
code

# import the random module
import random
  
  
# user defined function to shuffle
def sample_function():
    return 0.5
  
sample_list = ['A', 'B', 'C', 'D', 'E']
print("Original list : ")
print(sample_list)
  
# as sample_function returns the same value
# each time, the order of shuffle will be the
# same each time
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)

chevron_right


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']



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.