Choose from list python

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

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.choice s (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.

Way to generate random samples in Python

Table of contents

How to use random.sample()

It returns a new list containing the randomly selected items.

Syntax

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.
Читайте также:  What is name attribute in html

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

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

import random aList = [20, 40, 80, 100, 120] sampled_list = random.sample(aList, 3) print(sampled_list) # Output [20, 100, 80]

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.

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

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.

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

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.

Читайте также:  Html css font family size

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

import random # create list of 5 random numbers num_list = random.sample(range(100), 5) print(num_list) # output [79, 49, 6, 4, 57]

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

import random # create list of 5 numbers num_list = random.sample(range(100), 10) random.shuffle(num_list) print(num_list) # output [90, 36, 63, 37, 23, 11, 30, 68, 99, 5]

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 .

import random aSet = # random 3 samples from set sampled_set = random.sample(aSet, 3) print(sampled_set) # Output ['Emma', 'kelly', 'Eric']

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.

import random marks_dict = < "Kelly": 55, "jhon": 70, "Donald": 60, "Lennin": 50 >sampled_dict = random.sample(marks_dict.items(), 2) print(sampled_dict) # Output [('Donald', 60), ('jhon', 70)] # Access key-value from sample # First key:value print(sampled_dict[0][0], sampled_dict[0][1]) # Output jhon 70 # Second key:value print(sampled_dict[1][0], sampled_dict[1][1]) # output Kelly 55

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

import random # Randomly select same sample list every time alist = [20.5, 40.5, 30.5, 50.5, 70.5] for i in range(3): # use 4 as a seed value random.seed(4) # get sample list of three item sample_list = random.sample(alist, 3) print(sample_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.

Читайте также:  Java method signature ljava lang string

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.

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 3 sample rows 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 3 sample rows from 2D array [ 8 16 24] [ 7 14 21]

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() .

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.

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

About Vishal

I’m Vishal Hule, Founder of PYnative.com. I am a Python developer, and I love to write articles to help students, developers, and learners. Follow me on Twitter

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 10 questions
  • Each Quiz contains 12-15 MCQ

Источник

Оцените статью