In this article, we will learn how to use the `random.sample()`

function to choose multiple items from a list, set, and dictionary. Python’s random module provides `random.sample()`

function for random sampling and **randomly pick more than one element from the list without repeating elements**. The `random.sample()`

returns a list of *unique elements* chosen randomly from the list, sequence, or set, we call it random sampling without replacement.

In simple terms, for example, you have a list of 100 names, and you want to choose ten names randomly from it without repeating names, then you must use `random.sample()`

.

**Note**: If you want to randomly choose only a single item from the list then use random.choice().

**After reading this article**, you’ll learn the following usage of `random.sample()`

- Randomly select multiple items from a list, set, and dictionary.
- Randomly select multiple items from a list allowing repeated/duplicate items in the result( sample with replacement)
- Generate the sample of random integers in Python
- Get the same sampled list every time randomly
- Generate a random sample array from a sizeable multidimensional array in Python

**Recommended**

## How to use Python’s random.sample()

**The Syntax of random.sample()**

random.sample(population, k)

**Arguments**

The `random.sample()`

function has two arguments, and both are required.

- The
`population`

can be any sequence such as list, set from which you want to select a`k`

length number. - The
`k`

is the number of random items you want to select from the sequence.`k`

must be less than the size of the specified list. - A
`random.sample()`

function raises a type error if you miss any of the required arguments.

The `random.sample()`

returns a new list containing the randomly selected items. Now, let see how to use the `random.sample()`

function to select multiple items from a list.

### Python random.sample() example to select multiple items from a list without repeating

In this example, we will choose 3 random items from a list.

import random aList = [20, 40, 80, 100, 120] print ("choosing 3 random items from a list using random.sample() function") sampled_list = random.sample(aList, 3) print(sampled_list)

Output: Run Online

choosing 3 random items from a list using random.sample() function [40, 120, 100]

**Note**: As you can see the `random.sample()`

function doesn’t repeat the items in the result list. This is also called a random sample without replacement. If you want to generate random samples without replacement out of a list or population then you should use `random.sample()`

.

### Points to remember about Python random.sample()

- It is used for random sampling without replacement.
- It doesn’t change the specified sequence or list. It returns a new sampled list containing elements from the specified sequence or list.
- The specified list or population need not be hashable or unique.

**Important Note**:

**If your list itself contains repeated or duplicate** elements, then `random.sample()`

can pick repeated items because each occurrence is a possible selection in the sample. I.e., The `random.sample()`

can pick the repeated items from the specified list if the unique members are less than a sampling size.

Let’s see the example which demonstrates the same.

import random exampleList = [20, 40, 20, 20, 40, 60, 70] print ("choosing 4 random items from a list using random.sample() function") sampled_list2 = random.sample(exampleList, 4) print(sampled_list2)

Output: Run Online

choosing 4 random items from a list using random.sample() function [60, 40, 40, 20]

Also, don’t forget to solve our Python random data generation exercise.

## Python random.sample() with replacement to including repetition

Randomly select multiple items from a list with replacement. This process can repeat one of the elements.

For example, You have a list of names, and you want to choose random four names from it, and **it’s okay for you if one of the names repeats**, then it also possible. but to accomplish this, we cannot use `random.sample()`

. We can do that using a `random.choice`

function introduced in Python 3.6. Let see this with an example.**s**()

import random names = ["Roger", "Nadal", "Novac", "Andre", "Sarena", "Mariya", "Martina"] print("random sample with replacement to including repetition") samplelist3 = random.choices(names, k=3) print(samplelist3)

Output: Run Online

random sample with replacement to including repetition ['Martina', 'Nadal', 'Martina']

## Generate the sampled list of random integers in Python

I know you can use random.randint() and random.randrange() to generate the random numbers, but it can repeat the numbers. Is there a method/module to create a list of unique random numbers?

**Use random.sample() to create a list of random numbers without duplicates. **We need to use the combination of range() function and

`random.sample()`

. Let’s see a random sample generator to generate 5 sample numbers from 1 to 100.import random print("create a sampled list of random numbers without duplicates") sampled_list4 = random.sample(range(100), 5) print(sampled_list4)

Output: Run Online

create a sampled list of random numbers without duplicates [57, 17, 37, 72, 19]

On top of it, you can use random.shuffle() to shuffle the list of a sample of random integers.

import random sampled_List6 = random.sample(range(100), 5) print(sampled_List6) print("shuffled List of random sample numbers") random.shuffle(sampled_List6) print(sampled_List6)

Output: Run Online

[80, 87, 12, 36, 98] shuffled List of random sample numbers [98, 12, 80, 36, 87]

We used the range() with a `random.sample`

to generate a list of unique random numbers because it is fast, memory-efficient, and improves the performance for sampling from a large population.

## A random sample from the Python set

Same as the list, we can select random samples out of a set. Let’s see how to pick 3 random items from a Python set.

import random aSet = {"Jhon", "kelly", "Scoot", "Emma", "Eric"} print ("choosing 3 random items from a set using random.sample() ") sampled_set = random.sample(aSet, 3) print(sampled_set)

Output: Run Online

choosing 3 random items from a set using random.sample() ['kelly', 'Jhon', 'Scoot']

## The random sample from Python dictionary

Yes, it is possible to select a random key-value pair from the dictionary. As you know, `random.sample()`

function wants the population to be a sequence or set, and the dictionary is not a sequence. If you try to pass `dict`

directly you will get `TypeError: Population must be a sequence or set. For dicts, use list(d)`

So it would be best if you used `dict.items()`

to get all the dictionary items in the form of a list and pass it to the `random.sample()`

along with the sampling size (The number of key-value pairs you want to pick randomly out of `dict`

). Now, let’s see the example.

import random marks_dict = { "Kelly": 55, "jhon": 70, "Donald": 60, "Lennin": 50 } print ("choosing 2 random key-value pairs from a dictionary using random.sample() ") sampled_dict = random.sample(marks_dict.items(), 2) print(sampled_dict)

Output: Run Online

choosing 2 random key-value pairs from a dictionary using random.sample() [('Kelly', 55), ('Lennin', 50)]

## Python random sample seed to get the same sample list every time

It is possible to get the same sampled list of items every time from the specified list. We can do this by using random.seed() and `random.sample()`

function together. Let see this with an example.

import random print("Randomly select same sample list every time") alist = [20.5, 40.5, 30.5, 50.5, 70.5] random.seed(4) sample_list = random.sample(alist, 3) print("sampled list", sample_list) random.seed(4) sample_list = random.sample(alist, 3) print("sampled list", sample_list)

Output: Run Online

Randomly select same sample list every time sampled list [40.5, 30.5, 20.5] sampled list [40.5, 30.5, 20.5]

This is just a simple example. To get the same sampled list that you want every time you need to find the exact seed root number. Refer to this article on Python random.seed(): how to find the seed root.

## Get a sample array from a sizeable multidimensional array in Python.

Most of the time, we work with 2-d or 3-d arrays in Python. Let assume you want to pick more that one random rows from the multidimensional array then how to do it? Let see this with an example. In this example, we will use `numpy.random.choice()`

function to pick multiple random rows from the multidimensional array.

import numpy array = numpy.array([[2 ,4, 6], [5, 10, 15], [6, 12, 18], [7, 14, 21], [8, 16, 24]]) print("Printing 2D Array") print(array) print("Choose multiple random row from 2D array") randomRows = numpy.random.randint(5, size=2) for i in randomRows: print(array[i,:])

Output: Run Online

Printing 2D Array [[ 2 4 6] [ 5 10 15] [ 6 12 18] [ 7 14 21] [ 8 16 24]] Choose multiple random row from 2D array [2 4 6] [ 7 14 21]

Output: Run Online

**Note**: Above all, examples are not cryptographically secure. If you are doing this for any security-sensitive application then to cryptographically secure random output, use `random.SystemRandom().sample`

instead of `random.sample()`

.

Read more on how to generate random data in Python securely.

## random.sample() function Error and exception

A sample function can raise the following two errors.

`ValueError`

If the sample size is larger than the population (i.e., list or set) size`TypeError`

if any of the two arguments is missing.

## So What Do You Think?

I want to hear from you. What do you think of this article on Python random.sample()? Or maybe I missed one of the usages of `random.sample()`

. Either way, let me know by **leaving a comment below**.

Also, try to solve the following Free Python Exercises and Quizzes to have a better understanding of Working with random data in Python.

- Python random data generation Exercise to practice and master the random data generation techniques in Python.
- Python random data generation Quiz to test your random data generation concepts.