How to Shuffle a List in Python

Shuffle a Python list in place or return a new shuffled copy using the random module.

Easy Python 3.9+ Aug 9, 2026 Lists & loops 15 views 0 copies

Python code

12 lines
Python 3.9+
import 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

stdout
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

  1. Use `random.sample(items, len(items))` to return a shuffled copy directly
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Lists & loops

Related tutorials and quizzes for this topic.