How to Shuffle a List in Python
Shuffle a Python list in place or return a new shuffled copy using the random module.
Python code
12 linesimport random
def shuffle_list(items):
shuffled = items[:]
random.shuffle(shuffled)
return shuffled
if __name__ == "__main__":
original = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
result = shuffle_list(original)
print(f"Original: {original}")
print(f"Shuffled: {result}")
Output
Original: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Shuffled: [7, 2, 9, 5, 1, 10, 4, 3, 8, 6]
How it works
The random.shuffle function randomly reorders a list in place, modifying the original sequence. To avoid changing the original, we first copy the list with slicing items[:], then shuffle the copy. Each run produces a different random order, so exact output varies. The function returns the shuffled copy while preserving the input list untouched.
Common mistakes
- Forgetting to copy the list before shuffling, modifying the original
- Using `random.shuffle` on tuples or strings, which are immutable
- Expecting a reproducible shuffle without setting a random seed
Variations
- Use `random.sample(items, len(items))` to return a shuffled copy directly
- Set `random.seed(42)` before shuffling for deterministic, testable results
Real-world use cases
- Randomizing quiz question order for each test attempt to prevent memorization.
- Shuffling dataset rows before splitting into training and validation sets in ML.
- Randomizing a playlist or game deck order in a user-facing application.
Sponsored
More from Lists & loops
- Check if List is Sorted Ascending in Python easy
- Compare Two Lists in Python: Common, Only in First, Only in Second easy
- Convert a List of Integers to a Comma-Separated String in Python easy
- Enumerate a Python List with a Custom Start Index easy
- Extract Data by Type from a List in Python: Numbers and Strings easy
- Find All Occurrences of an Item in a Python List easy
Keep learning
Related tutorials and quizzes for this topic.