Python random shuffle() Method
The Python random shuffle() method randomly sorts all elements of a sequence.
Python random shuffle() Syntax
Here is the syntax of the shuffle() method:
import random random.shuffle (lst )
Note: shuffle() is not directly accessible, you need to import the random module and then call the method via the random static object.
Python random shuffle() Parameters
- lst : The list.
Python random shuffle() Return Value
Returns None.
Python random shuffle() Example#1
The following shows an example of using the shuffle() method.
#!/usr/bin/python3
import random
list = [20, 16, 10, 5];
random.shuffle(list)
print ("Random sorted list : ", list)
random.shuffle(list)
print ("Random sorted list : ", list)
Output:
Python random shuffle() Example#2
Since the sample_function returns the same value every time, the order of the shuffle will be the same every time.
#!/usr/bin/python3
import random
def sample_function():
return 0.5
sample_list = ['F', 'G', 'H', 'I', 'J']
print("Original list : ")
print(sample_list)
random.shuffle(sample_list, sample_function)
print("\nAfter the first shuffle : ")
print(sample_list)
sample_list = ['F', 'G', 'H', 'I', 'J']
random.shuffle(sample_list, sample_function)
print("\nAfter the second shuffle : ")
print(sample_list)
Output: