Python Program to Shuffle a List Using random.shuffle()
random.shuffle(your_list) to shuffle a list in Python in place, which rearranges the elements randomly.Examples
How to Think About It
random.shuffle() does this by swapping elements randomly inside the list.Algorithm
Code
import random my_list = [1, 2, 3, 4, 5] random.shuffle(my_list) print(my_list)
Dry Run
Let's trace the list [1, 2, 3, 4, 5] through the shuffle code
Original list
my_list = [1, 2, 3, 4, 5]
Call random.shuffle
random.shuffle(my_list) rearranges elements randomly
Shuffled list
my_list might become [3, 1, 5, 2, 4]
Print result
print(my_list) outputs the shuffled list
| Step | List State |
|---|---|
| Initial | [1, 2, 3, 4, 5] |
| After shuffle | [3, 1, 5, 2, 4] |
Why This Works
Step 1: Import random module
The random module provides functions to generate random numbers and shuffle lists.
Step 2: Use random.shuffle()
random.shuffle() rearranges the list elements in place, meaning it changes the original list order randomly.
Step 3: Print the shuffled list
Printing the list shows the new random order after shuffling.
Alternative Approaches
import random my_list = [1, 2, 3, 4, 5] shuffled_list = random.sample(my_list, len(my_list)) print(shuffled_list)
import random my_list = [1, 2, 3, 4, 5] for i in range(len(my_list)-1, 0, -1): j = random.randint(0, i) my_list[i], my_list[j] = my_list[j], my_list[i] print(my_list)
Complexity: O(n) time, O(1) space
Time Complexity
random.shuffle() runs in O(n) time because it swaps elements in the list once each, where n is the list length.
Space Complexity
It uses O(1) extra space since it shuffles the list in place without creating a new list.
Which Approach is Fastest?
random.shuffle() is fastest and most memory efficient compared to creating a new shuffled list with random.sample() which uses O(n) extra space.
| Approach | Time | Space | Best For |
|---|---|---|---|
| random.shuffle() | O(n) | O(1) | In-place shuffling, memory efficient |
| random.sample() | O(n) | O(n) | Creating a new shuffled list without changing original |
| Manual Fisher-Yates | O(n) | O(1) | Learning shuffle algorithm, custom control |