Shuffle a Python list
This post will discuss how to shuffle a list in Python. The solution should in-place shuffle the contents of a list.
1. Using random.shuffle
The standard solution to shuffle a list in Python is to use the shuffle() function from the random module. This is demonstrated below:
|
1 2 3 4 5 6 7 8 9 |
from random import shuffle if __name__ == '__main__': nums = list(range(10)) shuffle(nums) print(nums) |
2. Using random.sample
The shuffle() function shuffles the list in-place, i.e., the elements are rearranged within the list. To shuffle an immutable list, use sample() instead, which would return a new randomized list. This is demonstrated below:
|
1 2 3 4 5 6 7 8 9 |
from random import sample if __name__ == '__main__': nums = range(10) l = sample(nums, len(nums)) print(l) |
3. Using numpy.random.shuffle
If you’re using the NumPy library, consider using numpy.random.shuffle. It modifies the list in-place by shuffling its contents.
|
1 2 3 4 5 6 7 8 9 |
import numpy as np if __name__ == '__main__': nums = list(range(10)) np.random.shuffle(nums) print(nums) |
That’s all about shuffling a list in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)