Skip to content
DeveloperMemos

Shuffling a List in Python

Python, Lists, Shuffle1 min read

When working with lists in Python, you may come across situations where you need to shuffle the elements to achieve randomness or create a different order for processing the data. In this article, we'll cover different methods to shuffle a list in Python and provide examples to help you understand how to apply them effectively.

1. Using the random.shuffle() function

The random module in Python provides a built-in shuffle() function that shuffles the elements of a list in-place. This means that it modifies the original list directly, without returning a new list. Here's an example:

1import random
2
3my_list = [1, 2, 3, 4, 5]
4random.shuffle(my_list)
5print(my_list) # Output: [4, 2, 5, 1, 3]

2. Using the sorted() function with a custom key

Another approach to shuffling a list is by using the sorted() function along with a custom key. By providing a random value as the sorting key for each element, we can achieve a shuffled order. Here's an example:

1import random
2
3my_list = [1, 2, 3, 4, 5]
4shuffled_list = sorted(my_list, key=lambda x: random.random())
5print(shuffled_list) # Output: [3, 1, 2, 5, 4]

3. Using the numpy.random.shuffle() function

If you're working with large datasets or need more advanced functionalities for shuffling, you can utilize the numpy library. The numpy.random.shuffle() function is similar to the random.shuffle() function but works efficiently with multidimensional arrays. Here's an example:

1import numpy as np
2
3my_array = np.array([1, 2, 3, 4, 5])
4np.random.shuffle(my_array)
5print(my_array) # Output: [4, 2, 5, 1, 3]

4. Using list comprehensions and random sampling

List comprehensions provide a concise way to shuffle a list by randomly sampling elements and creating a new list. This approach doesn't modify the original list but generates a shuffled version. Here's an example:

1import random
2
3my_list = [1, 2, 3, 4, 5]
4shuffled_list = [x for x in random.sample(my_list, len(my_list))]
5print(shuffled_list) # Output: [5, 3, 2, 1, 4]

Wrapping Up

Shuffling a list in Python can be achieved using different techniques depending on your specific requirements. Whether you need to modify the list in-place or create a new shuffled version, the methods discussed in this article should provide the flexibility you need. Experiment with these techniques and choose the one that best fits your use case.