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.
Python code
15 linesimport 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
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
- Use `random.sample(range(n), k)` for sampling k distinct integers from 0 to n-1
- 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
More from Algorithms & data structures
- Binary Search for Ship Capacity in Python medium
- Binary Search on Answer in Python: Koko Eating Bananas medium
- Bucket Numbers into Histogram Bin Counts in Python easy
- Container With Most Water: Two-Pointer Solution in Python medium
- Count Smaller Elements to the Right in Python easy
- Depth First Search Traversal Order in Python easy
Keep learning
Related tutorials and quizzes for this topic.