Python random shuffle

Python random shuffle

Python randomshuffle() 

In this article, we will learn how to shuffle the Python list randomly using 
random.shuffle() function of a random module. Also, learn how to shuffle string or any sequence in Python randomly. When we say shuffle a list, it means we are rearranging the order of items in a list randomly.
The shuffle() method takes a sequence (list, string, or tuple) and reorganize the order of the items.

Note: This method changes the original list/tuple/string, it does not return a new list/tuple/string.

Syntax :


Parameter Values :

sequenceRequired. A sequence. Can be a list, a tuple, or a string.
functionOptional. The name of a function that returns a number between 0.0 and 1.0.
If not specified, the function random() will be used

Return Value :

The random.shuffle() shuffles in place and doesn't return anything i.e., It returns None. This function changes the position of items in a mutable sequence.

If you want to perform shuffling as per your need, then you can pass a custom random function in the place of a random argument, which will dictate shuffle function on how to randomizes the items of a list.

Shuffle a list using random.shuffle() :

#importing random module
import random

#initializing a list
my_list = ['c','p','p','s','e','c','r','e','t','s']
print("Original list:", my_list)

#first shuffle
print("List after first shuffle:", my_list)

#secong shuffle
print("List after second shuffle:", my_list)


Original list: ['c''p''p''s''e''c''r''e''t''s']                                                                             
List after first shuffle: ['p''p''s''c''c''t''r''e''e''s']                                                                  
List after second shuffle: ['r''c''p''e''t''s''c''p''s''e']

Note: As you can see in the output, the positions of list items are changed.

Shuffling a String :

If we try to rearrange a string's characters using random.shuffle() you will get an error.

The reason behind this is a string is immutable. And You can't modify the immutable objects in Python. The random.shuffle() function adjusts the position of the items. It changes the original object. The random.shuffle() doesn't work with String. I.e., It can't accept string argument. 

Let's understand this with the help of the following example.

 #importing random module
import random

#initializing a string
string = "cppsecrets"

#try to shuffle a string

Output :

We have a solution to this. We can shuffle a string using various approaches. Let see each one by one.

Approach One

  • Convert String to list
  • Shuffle the list randomly
  • Convert the shuffled list into String
#importing random module
import random

string = "cppsecrets"
print("Original String: ", string)

# convert string into list
char_list = list(string)

# shuffle list

# convert list to string
final_string = ''.join(char_list)
print("shuffled String is: ", final_string)


Original String:  cppsecrets                                                                                                                  
shuffled String is:  prptcesecs

Note: The above example shuffles the list in place. Let's see how to get shuffled a list of the original list without changing it.

Approach Two: Shuffling a String, not in place

Using this approach, we can have the original string unchanged and get the new shuffled string in return. Also, we don't need to convert string to list to get the shuffled string. i.e., To shuffle an immutable object like string and return a new shuffled string, we need to use random.sample(sampleStr, k=len(sampleStr)) instead.

#importing random module
import random

string = "cppsecrets"
print("Original String: ", string)

# shuffle string using random.sample()
final_string = ''.join(random.sample(string, len(string)))
print("shuffled string is: ", final_string)


Original String:  cppsecrets
shuffled string is:  eptcprssec

     ******END OF ARTICLE******

More Articles of Vishal Lodhi:

Name Views Likes
Python string zfill 114 0
Python string swapcase 92 0
Python string title 97 0
Python string startswith 103 0
Python string replace 144 0
Python string translate 85 0
Python string rpartition 85 0
Python string partition 74 0
Python string splitlines 114 0
Python string rsplit 79 0
Python string split 76 0
Python string rindex 82 0
Python string rfind 106 0
Python string upper 80 0
Python string lower 82 0
Python string maketrans 90 0
Python string strip 81 0
Python string rstrip 92 0
Python string lstrip 79 0
Python string rjust 96 0
Python string ljust 95 0
Python string len 82 0
Python string join 75 0
Python string casefold 82 0
Python string isprintable 85 0
Python string encode 78 0
Python string isdecimal 84 0
Python string isidentifier 78 0
Python string isupper 78 0
Python string istitle 80 0
Python string isspace 100 0
Python string isnumeric 102 0
Python string isdigit 83 0
Python string islower 84 0
Python string isalpha 96 0
Python string isalnum 102 0
Python string index 88 0
Python string find 93 0
Python string expandtabs() 81 0
Python string endswith 92 0
Python string count 86 0
Python string capitalize 78 0
Python string center 85 0
Python string Introduction 99 0
Python string Template 140 0
Python string Formatter 145 0
Python string printable 199 0
Python string whitespace 146 0
Python string punctuation 104 0
Python string octdigits 87 0
Python string hexdigits 104 0
Python string digits 80 0
Python string ascii_letters 344 0
Python string ascii_lowercase 147 0
Python string ascii_uppercase 156 0
How to Create Download Manager in Python 524 0
Python random weibullvariate 164 0
python random paretovariate 133 0
Python random vonmisesvariate 178 0
Python random normalvariate 196 0
Python random lognormvariate 120 0
Python random gauss 120 0
Python random gammavariate 131 0
Python random expovariate 194 0
Python random betavariate 186 0
Python random triangular 117 0
Python random uniform 141 0
Python random random 117 0
Python random sample 182 0
Python random shuffle 179 0
Python random choices 234 0
Python random choice 166 0
Python random randint 148 0
Python random randrange 214 0
Python random getrandbits 141 0
Python random setstate 136 0
Python random getstate 178 0
Python random seed 168 1
Python random Introduction 175 0