To shuffle a list in Python, you can use the shuffle
method from the random
module.
In this example,
shuffle
method from the random
module.numbers
with integer values.shuffle
method on the list object numbers
.shuffle
method randomly rearranges the elements in the list in place.import random
numbers = [1, 2, 3, 4, 5]
random.shuffle(numbers)
print(f'Shuffled list: {numbers}')
Shuffled list: [3, 1, 5, 4, 2]
In this example,
shuffle
method from the random
module.words
with string values.shuffle
method on the list object words
.shuffle
method randomly rearranges the elements in the list in place.import random
words = ['apple', 'banana', 'cherry', 'date', 'elderberry']
random.shuffle(words)
print(f'Shuffled list: {words}')
Shuffled list: ['cherry', 'elderberry', 'apple', 'banana', 'date']
In this tutorial, we learned How to Shuffle a List in Python language with well detailed examples.