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:

Download  Run Code

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:

Download  Run Code

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.

That’s all about shuffling a list in Python.