0
0
PythonHow-ToBeginner · 3 min read

How to Sample Multiple Elements from List in Python Easily

To sample multiple elements from a list in Python, use the random.sample() function which returns a new list of unique elements. Specify the list and the number of elements you want to sample as arguments, like random.sample(my_list, k).
📐

Syntax

The syntax for sampling multiple elements from a list is:

random.sample(population, k)

where:

  • population is the list (or any sequence) you want to sample from.
  • k is the number of unique elements you want to pick.

This function returns a new list with k unique elements chosen randomly without replacement.

python
import random

sampled_elements = random.sample(['a', 'b', 'c', 'd', 'e'], 3)
💻

Example

This example shows how to sample 3 unique elements from a list of 5 fruits.

python
import random

fruits = ['apple', 'banana', 'cherry', 'date', 'elderberry']
sample = random.sample(fruits, 3)
print(sample)
Output
['banana', 'date', 'apple']
⚠️

Common Pitfalls

Common mistakes when sampling multiple elements include:

  • Trying to sample more elements than the list contains, which raises a ValueError.
  • Using random.choice() instead of random.sample() when multiple unique elements are needed; random.choice() picks only one element.

Always ensure k is less than or equal to the length of the list.

python
import random

items = [1, 2, 3]

# Wrong: sampling more elements than list size
# sample = random.sample(items, 5)  # Raises ValueError

# Correct:
sample = random.sample(items, 2)
print(sample)
Output
[2, 1]
📊

Quick Reference

FunctionDescriptionNotes
random.sample(population, k)Returns a list of k unique elements sampled without replacementk must be ≤ len(population)
random.choice(sequence)Returns a single random elementUse for one element only
random.choices(sequence, k)Returns a list of k elements sampled with replacementDuplicates possible

Key Takeaways

Use random.sample() to pick multiple unique elements from a list without repeats.
Ensure the number of elements to sample does not exceed the list size to avoid errors.
random.choice() picks only one element; use random.sample() for multiple elements.
random.choices() allows duplicates because it samples with replacement.