How to Sample Random Items Without Replacement in Python

Select k random unique items from a sequence using random.sample for uniform, non-repeating selection.

Easy Python 3.9+ Aug 9, 2026 Algorithms & data structures 15 views 0 copies

Python code

15 lines
Python 3.9+
import random

def sample_without_replacement(population, k):
    """Return k random items from population without replacement."""
    if k > len(population):
        raise ValueError("k cannot exceed population size")
    # Use random.sample for O(k) time, no mutation of the original
    return random.sample(population, k)

if __name__ == "__main__":
    # Example: sample 3 fruits from a list of 6
    fruits = ["apple", "banana", "cherry", "date", "elderberry", "fig"]
    result = sample_without_replacement(fruits, 3)
    print("Sampled items:", result)
    print("Original list unchanged:", fruits)

Output

stdout
Sampled items: ['cherry', 'fig', 'apple']
Original list unchanged: ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig']

How it works

random.sample performs sampling without replacement in O(k) time by using a partial Fisher-Yates shuffle on a copy of the population, leaving the input sequence unmodified. It raises a ValueError if k exceeds the population length, which matches the Python API for random sampling. The function uses the system's randomness source by default, making it suitable for most non-security applications. This approach is both concise and idiomatic, avoiding manual index tracking or destructive list population.

Common mistakes

  • Forgetting to check if k exceeds population size before sampling, causing a ValueError from random.sample
  • Mutating the original list when implementing a manual shuffle-based approach
  • Using random.choices instead, which allows duplicates by design

Variations

  1. Use `random.sample(range(n), k)` for sampling k distinct integers from 0 to n-1
  2. Implement a manual Fisher-Yates shuffle on a list copy for educational clarity

Real-world use cases

  • Selecting a random subset of users for A/B testing or survey distribution.
  • Choosing k training rows from a dataset for mini-batch stochastic gradient descent.
  • Picking random support tickets for QA auditing without revisiting the same ticket twice.

Sponsored

Run this sample

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

Open editor

More from Algorithms & data structures

Related tutorials and quizzes for this topic.