How to use Random shuffle() Method in Python
In this tutorial, we will discuss how to use Random shuffle() Method in Python.
shuffle method is used for changing the position of elements in the list. shuffle()
is an inbuilt function of the random module. Shuffle is mainly used for interchanging the element positions in the list.
Note that shuffle()
method cannot shuffle immutable data types like strings.
Random shuffle() Method in Python
Syntax:
random.shuffle(sequence,function)
sequence: Required and Mutable data types like lists.
function: Optional and default function is random() or you can pass a function name that returns a number between 0.0 and 1.0.
Note that shuffle() method changes the original list and does not return new list.
Let’s see the code
# import random module import random Mylist = ['P', 'Q', 'R', 'S', 'T'] print("Original list: ") print(Mylist) # For first shuffle random.shuffle(Mylist) print("After first shuffle: ") print(Mylist) # For second shuffle random.shuffle(Mylist) print("After second shuffle: ") print(Mylist) # For third shuffle random.shuffle(Mylist) print("After third shuffle: ") print(Mylist)
Output:
Original list: ['P', 'Q', 'R', 'S', 'T'] After first shuffle: ['P', 'T', 'Q', 'R', 'S'] After second shuffle: ['R', 'Q', 'P', 'S', 'T'] After third shuffle: ['R', 'P', 'S', 'T', 'Q']
Let’s see the code by creating a function
# import random module import random def func(): return 0.2 Mylist = ['P', 'Q', 'R', 'S', 'T'] print("Original list: ") print(Mylist) # For first shuffle random.shuffle(Mylist,func) print("After first shuffle: ") print(Mylist) Mylist = ['P', 'Q', 'R', 'S', 'T'] # For second shuffle random.shuffle(Mylist,func) print("After second shuffle: ") print(Mylist) Mylist = ['P', 'Q', 'R', 'S', 'T'] # For third shuffle random.shuffle(Mylist,func) print("After third shuffle: ") print(Mylist)
Output:
Original list: ['P', 'Q', 'R', 'S', 'T'] After first shuffle: ['T', 'R', 'S', 'P', 'Q'] After second shuffle: ['T', 'R', 'S', 'P', 'Q'] After third shuffle: ['T', 'R', 'S', 'P', 'Q']
Here you can see that func()
returns the same value every time, so the order of shuffle will be the same every time.
Also read:
Leave a Reply