In this article, we will learn the random module’s sample method. We also learn when should it be used and examples that demonstrate it’s usage. The ** sample() **method

**returns a k length list of unique elements chosen from the population sequence or set**, used for random sampling without replacement.

- This article is part of our series
**Generate Random Data In Python.** - Solve our
**Free****Python random data generation Exercise.****And**to master random data generation techniques in Python.

Free Python Random data generation Quiz

In simple term, we use the `sample`

method to select a k length random number from a sequence or list in such a way that each number is unique. I.e., We use a `sample()`

method when we want to pick more than one random element from a sequence.

**For example**, `random.sample(population=[2,5,7,8,9], k=3)`

this will return `[7,5,8]`

. **Note** The `sample()`

method used for random sampling without replacement.

## The Syntax of random.sample

random.sample(population, k)

**Arguments**

sample method has two arguments, and both are required.

- The
**population can be any sequence or set**from which you want to select a`k`

length numbers. The sequence can be String, list. you want to select from the provided population.`k`

is the number of random items`sample`

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

**The return value from a sample method**

- A sample method
**returns a new list containing k length elements**from the list or sets. Remember the`sample`

method doesn’t change the original list or population. - The resulting list is in selection order so that all sub-slices also be valid random samples.
- A
`sample`

method returns a new list so you can perform any list operations on it.

Let see how to use the random.sample() method to select more than one item from a list.

## random.sample to select more than one item from a list

import random print("random module's sample in Python ") list = [20,40,80,100,120] print ("choosing 3 random items from a list using sample method ",random.sample(list,k=3)) list = [20,40,20,20,20] print ("choosing 3 random items from a list using sample method ",random.sample(list,k=3))

Output: **Execute Online**

random module's sample in Python choosing 3 random items from a list using sample method [80, 40, 100] choosing 3 random items from a list using sample method [20, 20, 20]

As you can see we pass `k=3`

to choose 3 random elements from a list. in return, we got a list of 3 random items.

**Note**: Members of the list need not be hashable or unique. It allows duplicate entries.

`k`

must be less than the size of the list.**If the list contains repeats, then each occurrence is a possible selection in the sample**. i.e., sample method can pick the repeated items from the list if the unique numbers are less than a sampling size.

## The random sample from Set

Same like the list we can select random samples without replacement out of a set. Let see this with an example program.

import random weight_set = {40, 50, 55, 65, 75,80} print ("choosing 4 random items from a set using sample method ",random.sample(weight_set, k=4))

Output: **Execute Online**

choosing 4 random items from a set using sample method [40, 75, 65, 80]

## The random sample from Dictionary

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

method wants the population to be a sequence or set.

So you need to pass all the dictionary items to the `sample()`

method along with the sampling size. You can use `dict.items()`

to get all the dictionary items.

Let see this with an example.

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

Output: **Execute Online**

choosing 2 random items from a dictionary using sample method [('Donald', 60), ('Kelly', 55)]

## random sample with replacement to including repetition

If you want to get a random sample with replacement, for example, You have a list of names, and you want to get random names from it, but including repetition then it also possible.

To do this, we cannot use the `sample`

method. We can do that using a ** choices** method that introduced in Python 3.6. Let see this with an example.

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

Output: **Execute Online**

random sample with replacement to including repetition ['Mariya', 'Mariya', 'Andre']

**random sample without replacement**: – If you want to generate random samples without replacement out of a list or population then use sample method.

## The random sample from a range of integers

Generating a sample from a range of an integer is possible. You need to pass a range object to a `sample`

method in the place of population argument. Let see this with an example.

import random print ("choosing 4 random items from a set ",random.sample(weight_set, k=4))

Output:

choose random numbers from a range using sample method [39, 21, 41, 23, 37, 13, 35, 27]

Why use the range with sample method to pick random numbers? Because it is fast, memory efficient and improves the performance for sampling from a large population.

## Get the same sample list every time

It is possible to get the same list of items every time from sample method. We can do this by using **seed** and `sample`

method. let see this with an example.

import random list = [20.5, 40.5, 30.5, 50.5, 70.5] random.seed(4) sample_list = random.sample(list, 3) print("random List", sample_list) random.seed(4) sample_list = random.sample(list, 3) print("random List", sample_list)

Output: **Execute Online**

random List [40.5, 30.5, 20.5] random List [40.5, 30.5, 20.5]

To get the same sampled list that you want every time you need to find seed root. Refer to this article to find the seed root of your sampled list.

## Get a sample array from a large 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 multidimensional array then how to do it? Let see this with an example. In this example, We used `numpy.random.choice()`

method 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:

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 [ 8 16 24] [2 4 6]

**Note: Above all examples are not cryptographically secure**. To cryptographically secure random output use `random.SystemRandom().sample`

instead of `random.sample`

## Random sample method Error and exception

A `sample`

method 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.

## Next Steps

To practice what you learned in this article, I have created a Python random data generation Quiz and Exercise project.

- Solve our
**Python Random data generation Quiz**to test your random data generation concepts. - Solve the
**Free Random data generation Exercise**to practice and master the random data generation techniques in Python.

Let me know your comments and feedback in the section below.

masterdrew950 says

How would I use the last code “Get a sample array from a large multidimensional array in Python” but instead of the whole array be able to pick one or more item from and array to create a new array with index from witch they came:

Printing 2D Array

A1, A2, A3

0 [[ 2 4 6]

1 [ 5 10 15]

2 [ 6 12 18]

3 [ 7 14 21]

4 [ 8 16 24]]

out put: 2, 10, 14 = [A1,0], [A2,1], [A2,3]

out put: 12, 10, 8 = [A2,2], [A3,2], [A1,4]

is this even possible?

Vishal says

Hey masterdrew950, Sorry I didn’t get you. I could not understand the context of your statement. can you please elaborate the issue