PYnative

Practice Coding

  • Python â–¼
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Coding Exercises â–¼
    • Python Exercises
    • C++ Exercises
    • C Programming Exercises
    • Java Exercises
    • C# Exercises
  • MCQsâ–¼
    • Python MCQ Quizzes
    • Java MCQ Quizzes
    • C++ MCQ Quizzes
  • Compilersâ–¼
    • Online Python Compiler
    • Online C Compiler
    • Online C++ Compiler
    • Online Java Compiler
    • Online C# Compiler
Home » Python » Random » Python random sample() to choose multiple items from any sequence

Python random sample() to choose multiple items from any sequence

Updated on: December 4, 2026 | 16 Comments

In this tutorial, you’ll learn how to use random.sample() to pick multiple unique items from a list, string, set or dictionary, and how to take a random sample of rows from a NumPy array.

The sample() function of the random module returns a new list of k items chosen randomly from a population, without replacement: no position is picked twice. For example, if you have a list of 100 names and want 10 different names, use random.sample().

Note: To pick a single item, use random.choice() instead.

OperationDescription
random.sample(seq, k)Return k unique items from a list, tuple, string or range (sampling without replacement)
random.choices(seq, k=n)Return n items that may repeat (sampling with replacement)
random.sample(range(100), 5)Return 5 unique random integers from 0 to 99
random.sample(sorted(a_set), 2)Return 2 random items from a set
random.sample(list(d.items()), 2)Return 2 random key-value pairs from a dictionary
Ways to generate random samples in Python

Also, Solve:

  • Python random data generation Exercise
  • Python random data generation Quiz

Table of contents

  • How to use random.sample()
    • Syntax
    • Example: select multiple items from a list without repetition
    • Points to remember about random.sample()
  • Random sample with replacement (repeats allowed)
  • Generate a list of unique random integers
  • Random sample from a string
  • A random sample from a set
  • Random sample from a dictionary
  • Repeat elements using the counts parameter
  • Get the same sample every time
  • Get random rows from a multidimensional array
  • Secure random sample
  • random.sample() errors
  • Summary

How to use random.sample()

Syntax

random.sample(population, k, *, counts=None)Code language: Python (python)
  • population: a sequence such as a list, tuple, string or range. Sets and dictionaries must be converted first (see below).
  • k: the number of items to select. It must be between 0 and the population size.
  • counts (optional, Python 3.9+): how many times each element appears in the population.

It returns a new list with k randomly selected items.

Example: select multiple items from a list without repetition

import random

a_list = [20, 40, 80, 100, 120]
sampled_list = random.sample(a_list, 3)
print(sampled_list)
print(a_list)  # the original list is unchangedCode language: Python (python)

Output (your result may differ):

[120, 80, 100]
[20, 40, 80, 100, 120]

Points to remember about random.sample()

  • It doesn’t modify the original sequence; it returns a new list.
  • The elements don’t need to be hashable or unique.
  • Each position is picked at most once. If the population contains duplicate values, the sample can contain them too.
import random

example_list = [20, 40, 20, 20, 40, 60, 70]
# 20 appears three times, so it can be picked more than once
print(random.sample(example_list, 4))Code language: Python (python)

Output:

[20, 60, 40, 20]

Tip: To sample unique values, remove duplicates first: random.sample(sorted(set(example_list)), 3).

Random sample with replacement (repeats allowed)

If the same item may be picked more than once, use random.choices() (Python 3.6+). Unlike sample(), k can be larger than the population.

import random

names = ["Roger", "Rafael", "Novak", "Andre", "Serena", "Maria", "Martina"]

# 3 random names; a name can repeat
print(random.choices(names, k=3))Code language: Python (python)

Output:

['Maria', 'Maria', 'Rafael']

Generate a list of unique random integers

random.randint() can return the same number twice. To get unique random integers, pass a range() to sample(). A range doesn’t store its numbers in memory, so this is fast even for very large ranges.

import random

# 5 unique numbers from 0 to 99
print(random.sample(range(100), 5))

# lottery: 6 unique numbers from 1 to 49
print(random.sample(range(1, 50), 6))Code language: Python (python)

Output:

[6, 20, 14, 47, 60]
[16, 25, 35, 7, 37, 49]

Tip: random.sample(a_list, k=len(a_list)) returns a shuffled copy of a list without changing the original. See how to shuffle a list.

Random sample from a string

A string is a sequence, so sample() returns a list of random characters. Use "".join() to turn it back into a string.

import random

chars = random.sample("PYnative", 3)
print(chars)
print("".join(chars))Code language: Python (python)

Output:

['e', 'Y', 'v']
eYv

A random sample from a set

Since Python 3.11, sample() no longer accepts a set and raises TypeError: Population must be a sequence. For dicts or sets, use sorted(d). Convert the set to a sorted list first. Sorting also makes the result reproducible when you use a seed.

import random

a_set = {"John", "Kelly", "Scott", "Emma", "Eric"}

# 3 random items from a set
print(random.sample(sorted(a_set), 3))Code language: Python (python)

Output:

['Emma', 'Eric', 'Kelly']

Random sample from a dictionary

A dictionary isn’t a sequence either. Convert its items to a list, then sample key-value pairs.

import random

marks_dict = {"Kelly": 55, "John": 70, "Donald": 60, "Lenin": 50}

sampled_items = random.sample(list(marks_dict.items()), 2)
print(sampled_items)

for name, marks in sampled_items:
    print(name, marks)Code language: Python (python)

Output:

[('Donald', 60), ('Kelly', 55)]
Donald 60
Kelly 55

Use dict(sampled_items) if you need the result as a dictionary.

Repeat elements using the counts parameter

The counts argument (Python 3.9+) lets you describe a population with repeated elements without building the full list. For example, a bag with 3 red balls and 2 blue balls:

import random

# same as sampling from ['red', 'red', 'red', 'blue', 'blue']
print(random.sample(["red", "blue"], counts=[3, 2], k=4))Code language: Python (python)

Output:

['blue', 'red', 'red', 'red']

Get the same sample every time

To reproduce a sample, for example in tests, set the same value with random.seed() before calling sample().

import random

a_list = [20.5, 40.5, 30.5, 50.5, 70.5]

for i in range(3):
    random.seed(4)
    print(random.sample(a_list, 3))Code language: Python (python)

Output:

[40.5, 30.5, 20.5]
[40.5, 30.5, 20.5]
[40.5, 30.5, 20.5]

Get random rows from a multidimensional array

To pick several random rows from a 2D NumPy array without repeating any row, use the choice() method of a NumPy Generator with replace=False.

import numpy as np

rng = np.random.default_rng()
array = np.array([[2, 4, 6], [5, 10, 15], [6, 12, 18], [7, 14, 21], [8, 16, 24]])

# 3 unique random rows
print(rng.choice(array, size=3, replace=False))Code language: Python (python)

Output:

[[ 6 12 18]
 [ 5 10 15]
 [ 7 14 21]]

Secure random sample

The random module is predictable and not suitable for security. For security-sensitive samples, use a cryptographically secure random generator: random.SystemRandom().sample(). Read more in the secrets module tutorial.

import random

secure_random = random.SystemRandom()
print(secure_random.sample(range(10), 3))Code language: Python (python)

random.sample() errors

  • ValueError: Sample larger than population or is negative: k is greater than the population size or negative.
  • TypeError: Random.sample() missing 1 required positional argument: 'k': you didn’t pass k.
  • TypeError: Population must be a sequence: you passed a set or dictionary (Python 3.11+).

Practice Problem:

A class has 10 students. Randomly pick 3 different students to present today and print their names.

Show Solution
import random

students = ["Amy", "Ben", "Cara", "Dan", "Eva", "Finn", "Gia", "Hugo", "Ivy", "Jack"]
presenters = random.sample(students, 3)
print("Today's presenters:", ", ".join(presenters))Code language: Python (python)

Summary

  • random.sample(population, k) returns k items without picking any position twice.
  • Use random.choices() when repeats are allowed.
  • Convert sets with sorted() and dictionaries with list(d.items()) before sampling.
  • Use random.seed() for reproducible samples and SystemRandom for secure ones.

Now test what you’ve learned with the Python random data generation exercise and quiz.

Filed Under: Python, Python Random

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

Python Python Random

All Coding Exercises:

C Exercises
C++ Exercises
Python Exercises
Java Exercises
C# Exercises

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 25+ questions
  • Each Quiz contains 25 MCQ
Exercises
Quizzes
In: Python Python Random
TweetF  sharein  shareP  Pin

  Python Random Data

  • Guide to Generate Random Data
  • Random randint() & randrange()
  • Random Choice
  • Random Sample
  • Weighted random choices
  • Random Seed
  • Random Shuffle
  • Get Random Float Numbers
  • Generate Random String
  • Generate Secure random data
  • Secrets to Secure random data
  • Random Data Generation Exercise
  • Random Data Generation Quiz

 Explore Python

  • Python Tutorials
  • Python Exercises
  • Python Quizzes
  • Python Interview Q&A
  • Python Programs

All Python Topics

Python Basics Python Exercises Python Quizzes Python Interview Python File Handling Python OOP Python Date and Time Python Random Python Regex Python Pandas Python Databases Python MySQL Python PostgreSQL Python SQLite Python JSON

About PYnative

PYnative.com is a platform built to help developers learn by doing. Solve coding exercises, take MCQs, and run code directly in built-in online compilers.

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Coding Exercises

  • C Exercises
  • C++ Exercises
  • Python Exercises
  • Java Exercises
  • C# Exercises

MCQ Quizzes

  • Python MCQs
  • Java MCQs
  • C++ MCQs

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our:

  • Terms Of Use
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2026 pynative.com