How to shuffle a list in Python?

Table of Contents

Introduction

Shuffling a list in Python is a common task when you need to randomize the order of elements within a list. This can be useful in various scenarios, such as creating randomized test data, shuffling a deck of cards, or randomizing the order of questions in a quiz. Python provides a straightforward way to shuffle a list using the random module.

Methods to Shuffle a List in Python

Using random.shuffle()

The most common and direct way to shuffle a list in Python is by using the shuffle() function from the random module. This method modifies the original list in place, meaning the order of elements is changed directly in the list you pass to the function.

Example:

In this example, random.shuffle() randomizes the order of elements in my_list. The list is modified in place, so no new list is created.

Using random.sample()

Another way to shuffle a list is by using the sample() function from the random module. Unlike shuffle(), random.sample() does not modify the original list. Instead, it returns a new list containing the elements of the original list in a shuffled order.

Example:

In this example, random.sample() returns a new list with the elements of my_list shuffled, while my_list itself remains unchanged.

Practical Examples

Example 1: Shuffling a Deck of Cards

If you were to simulate shuffling a deck of cards, you could use random.shuffle() to randomize the order of the cards in the deck.

This example shows how you can shuffle a list representing a deck of cards.

Example 2: Randomizing the Order of Quiz Questions

If you're building a quiz application, you might want to randomize the order of questions each time the quiz is presented.

In this example, random.shuffle() randomizes the order of the quiz questions, ensuring that each quiz session presents the questions in a different order.

Conclusion

Shuffling a list in Python is a straightforward task that can be accomplished using the random.shuffle() function to modify the list in place or random.sample() to create a new shuffled list while keeping the original list unchanged. Whether you're shuffling a deck of cards, randomizing quiz questions, or simply mixing up data, these methods provide an easy and efficient way to introduce randomness into your list.

Similar Questions