Shuffle Python List
Shuffle List in Python
List is an ordered sequence of items. You can shuffle these items using shuffle() function of random module.
shuffle() function takes a sequence and shuffles the order of elements.
Following is the quick code snippet to shuffle a list.
random.shuffle(listA)
Examples
1. Shuffle a given list of numbers
In this example, we take a list of numbers, and shuffle this list using random library.
Python Program
import random
# Take a list of numbers
listA = [2, 8, 4, 3, 1, 5]
# Shuffle the list
random.shuffle(listA)
print(listA)
Output
When the above program is run, it prints a shuffled list. We have run it many times, to see the order of elements change.
2. Shuffle a given list of strings
In this program, we shall take a list of string and shuffle them.
Python Program
import random
# Take a list of strings
listA = ['a', 'b', 'c', 'd', 'e']
# Shuffle the list
random.shuffle(listA)
print(listA)
Output
During each run, the list of strings is shuffled.
Summary
In this tutorial of Python Examples, we learned how to shuffle a list, with the help of well detailed examples.