Open In App

Ways to shuffle a list in Python

Last Updated : 11 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Shuffling a list means rearranging its elements in a random order. For example, if you have a list a = [1, 2, 3, 4, 5], shuffling it might result in [3, 1, 5, 2, 4]. Let’s explore the most efficient and commonly used methods to shuffle a list in Python.

Using random.shuffle()

random.shuffle() function is simplest way to shuffle a list in-place. It directly modifies the list and doesn't return a new list.

Python
import random

a = [1, 2, 3, 4, 5]
random.shuffle(a)
print(a)

Output
[2, 4, 3, 5, 1]

Explanation: random.shuffle(a) shuffles the list a in place by modifying the original list directly.

Using numpy.random.shuffle()

numpy.random.shuffle() is a NumPy-specific shuffling method that also shuffles the array in-place. It’s particularly efficient for large numerical datasets and ideal when you're already working with NumPy arrays.

Python
import numpy as np

a = np.array([1, 2, 3, 4, 5])
np.random.shuffle(a)
print(a.tolist())

Output
[4, 1, 3, 5, 2]

Explanation:

  • np.random.shuffle(a) shuffles a in-place, just like random.shuffle(), but optimized for NumPy's internal memory layout.
  • a.tolist() converts the NumPy array back to a list.

Using random.sample()

If we don't want to modify the original list then use random.sample() to generate a shuffled copy. This method returns a new list with shuffled elements.

Python
import random

a = [1, 2, 3, 4, 5]
b = random.sample(a, len(a))
print(b)

Output
[4, 1, 5, 3, 2]

Explanation: random.sample(a, len(a)) creates a new shuffled list with elements from a. The second argument len(a) specifies that we want all elements in the shuffled list.

Using sorted() with random Keys

We can also use sorted() with a random key to get a new shuffled list but this method is not commonly used to shuffle a list.

Python
import random

a = [1, 2, 3, 4, 5]
b = sorted(a, key=lambda x: random.random())
print(b) 

Output
[2, 4, 3, 5, 1]

Explanation:

  • sorted(a, key=lambda x: random.random()) sorts list 'a' using a random key for each element and create a new shuffled list.
  • key=lambda x: random.random() assigns a random key to each element which results in random sorting.

Practice Tags :

Similar Reads