In this lesson, you will learn how to use the `random.sample()`

function to choose sample/multiple items from a Python list, set, and dictionary. We will also see how to generate a random sample array from a sizeable multidimensional array in Python.

Python’s random module provides a `sample()`

function for random sampling, randomly picking more than one element from the list without repeating elements. It returns a list of unique items 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**: Use the random.choice() function if you want to choose only a single item from the list.

**You’ll learn the following ways to generate random samples in Python**

Operation | Description |
---|---|

`random.sample(seq, n)` | Generate `n` unique samples (multiple items) from a sequence without repetition. Here, A `seq` can be a `list` , `set` , `string` , `tuple` . Sample without replacement. |

`random.choices(seq, n)` | Generate `n` samples from a sequence with the possibility of repetition. Sample with replacement |

`random.sample(range(100), 5)` | Return the sampled list of unique random integers. |

`random.sample(d1.items(), 2)` | Returns two key-value pairs from Python dictionary. |

## Table of contents

- How to use random.sample()
- random sample with replacement to including repetitions
- Generate the sampled list of random integers
- A random sample from the Python set
- Random sample from Python dictionary
- Random seed to get the same sample list every time
- Get a sample array from a multidimensional array
- random.sample() function Error and exception
- Next Steps

## How to use `random.sample()`

It returns a new list containing the randomly selected items.

**Syntax**

`random.sample(population, k)`

Code language: Python (python)

**Arguments**

The `sample()`

function takes two arguments, and both are required.

`population`

: It can be any sequence such as a list, set, and string from which you want to select a k length number.`k`

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

must be less than the size of the specified list.- It raises a
`TypeError`

if you miss any of the required arguments.

### random sample() example to select multiple items from a list without repetition

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

As you can see in the output, the `sample()`

function doesn’t repeat the list items. It is also called a random **sample without replacement**. So use it to generate random samples without repetitions.

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

- 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 sequence need not be hashable or unique.

**Important Note**: If your list contains repeated or duplicate elements, then `sample()`

can pick repeated items because each occurrence is a possible selection in the sample. It chooses 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.

## random sample with replacement to including repetitions

Use the random.choices() function to select multiple random items from a sequence with repetition. 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.

A `random.choices()`

function introduced in Python 3.6. Let see this with an example.

## Generate the sampled list of random integers

You can use `random.randint()`

and `random.randrange()`

to generate the random numbers, but it can repeat the numbers. To create a list of unique random numbers, we need to use the sample() method.

Warp a range() function inside a `sample()`

to create a list of random numbers without duplicates. The range() function generates the sequence f random numbers.

Let’s see a random sample generator to generate 5 sample numbers from 1 to 100.

On top of it, you can use the `random.shuffle()`

to shuffle the list of random integers.

**Note**: 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

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

.

## Random sample from Python dictionary

Python Dictionary is an unordered collection of unique values stored in (Key-Value) pairs.

The `sample()`

function requires 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`

.

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

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

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

Let’s see the example to select a two samples of key-value pair from the dictionary.

## Random seed to get the same sample list every time

Seed the random generator to get the same sampled list of items every time from the specified list.

Pass the same seed value every time to get the same sampled list

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

**Note**: To get the same sampled list every time, you need to find the exact seed root number.

## Get a sample array from a multidimensional array

Most of the time, we work with 2d or 3d arrays in Python. Let assume you want to pick more than one random row from the multidimensional array. Use the `numpy.random.choice()`

function to pick multiple random rows from the multidimensional array.

Output Printing 2D Array [[ 2 4 6] [ 5 10 15] [ 6 12 18] [ 7 14 21] [ 8 16 24]] Choose 3 sample rows from 2D array [ 8 16 24] [ 7 14 21]

**Note**:

The above all examples are not cryptographically secure. If you are creating samples for any security-sensitive application, then use a cryptographically secure random generator, use the `random.SystemRandom().sample()`

instead of `random.sample()`

.

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

`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 or sequence (i.e., list or set) size.`TypeError`

: If any of the two arguments is missing.

## Next Steps

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 exercise and quiz to have a better understanding of Working with random data in Python.