PYnative

Python Programming

  • Learn Python
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Exercises
    • Python Exercises
    • C Programming Exercises
    • C++ Exercises
  • Quizzes
  • Code Editor
    • Online Python Code Editor
    • Online C 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: July 25, 2021 | 16 Comments

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

OperationDescription
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.
Way to generate random samples in Python

Also, See:

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

Table of contents

  • How to use random.sample()
    • Syntax
    • random sample() example to select multiple items from a list without repetition
    • Points to remember about 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.

import random

aList = [20, 40, 80, 100, 120]
sampled_list = random.sample(aList, 3)
print(sampled_list)
# Output [20, 100, 80]Code language: Python (python)

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]Code language: Python (python)

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']Code language: Python (python)

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.

import random

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

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]Code language: Python (python)

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 = {"Jhon", "kelly", "Scoot", "Emma", "Eric"}
# random 3 samples from set
sampled_set = random.sample(aSet, 3)
print(sampled_set)
# Output ['Emma', 'kelly', 'Eric']Code language: Python (python)

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 55Code language: Python (python)

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)Code language: Python (python)
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.

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, :])Code language: Python (python)
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.

  • Python random data generation Exercise
  • Python random data generation 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

Image

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

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

Comments

  1. ImageDonald McLachlan says

    June 27, 2024 at 8:09 pm

    Re: num_list = random.sample(range(100), 5)

    I believe that creates a list of 5 random numbers between 0 and 99, not between 1 and 100.

    Reply
  2. ImageKatie B. says

    April 3, 2022 at 4:11 am

    Hi Vishal,

    Thank you for this beneficial article! I would like to know how to use random.sample() within a for-loop to generate multiple sample lists that are NOT identical. Essentially, the opposite of the section “Random seed to get the same sample list every time”. For example, right now, I have:

    
    for i in range(3):
    sample=random.sample(range(10), k=2)

    This will generate 3 sample lists containing two numbers each, but I would like to make sure none of those sample lists are identical. (It is okay if there are repeating values, i.e., (2,1), (3,2), (3,7) would be okay, but (2,1), (1,2), (5,4) would not.)

    Would you please guide me as to how to do this most efficiently? Thank you!

    Cheers,
    Katie

    Reply
  3. Imagegidi says

    October 27, 2020 at 6:48 pm

    thank you for example, how to randomly select images from the folder and save them as random samples/to another folder. let me say you wish to randomly select 500 images from the folder containing 8000 images without repetitions of images. Thank you

    Reply
  4. ImageRuss Abbott says

    June 21, 2020 at 1:47 am

    Is it possible to write a version of sample that works as a generator rather than producing a complete list? Assume I have a set (st) and want to iterate over that set in a random order, but I don’t want to copy or change the set.

    for element in sample(st, len(st)):
      
    

    The problem with the preceding is that it copies the set (in a random order) before doing the for-loop.

    Reply
  5. Imageanıl says

    April 1, 2020 at 3:12 pm

    Hello

    from random import sample
    
    list1 = (['wqe', 'asd', 'xzc'])  
      
    print(sample(list1, 1))
    

    this code and output always [‘ ‘] for example:
    [‘xzc’]
    how do i get rid of those quotes and braces?

    Reply
    • ImageVishal says

      April 1, 2020 at 3:40 pm

      Hi, Anil random.sample() method always returns the list of random samples. You are getting the Python list with one element because you are choosing 1 random item from the list. If you want only one random item from the list, please use random.choice()

      Reply
      • Imageanıl says

        April 1, 2020 at 11:17 pm

        but i want unique items like

        import time
        import random
        a = 1
        while True:
            if a == 1:
                list1 = 'we' , 'asd' , 'cvx' , 'dfgfg' , 'fghrt' , 'ryyer'   
                print(random.sample(list1, 1)) 
                time.sleep(1)
        

        this code isn’t unique, but the article says random.sample gives item with ”unique” attribute

        Reply
        • ImageVishal says

          April 2, 2020 at 7:17 pm

          Anil, It will not repeat the elements in a single call. You are calling the random.sample() method repeatedly. It’s altogether a new call. if you do random.sample(list1, 2) it will return any two items from the list without repeating. if your list itself contains repetitive stings then it can repeat items.

          Let me know if it helps you.

          Reply
  6. Imagejon says

    February 17, 2020 at 6:38 pm

    hi vishal, when using a list, I saw that I cannot add or subtract the sample I took from the list. For example:

    import random
    x = random.sample ((1 ,2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13), k=1 )
    print(x + 1)
    

    Why can’t I add unto the list I created, and how can I get around that issue?

    Reply
    • ImageVishal says

      February 18, 2020 at 6:08 pm

      Hi Jon, we cannot concatenate the list with int type. we need to convert 1 into a list

      import random
      x = random.sample ((1 ,2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13), k=1 )
      print(x + list([1]))
      Reply
  7. ImageVusumuzi Zikalala says

    February 6, 2020 at 3:22 pm

    Hi,
    Thanks for the example. I want to know how to access the random list output from random.sample () and be able to select each number inside the list and also sort it they way i want. Here is my code below.

    print("5  numbers")
        RN = [print(random.sample (fn,5))]
        print ("RN IS A",type(RN))
        print (RN.sort()) [## this function cant access RN and cant sort it and it prints None]
        print ("RN[0]",RN[0]) [##This should give me the first index in my list but it prints None]
        RP = [print(random.sample (fpn,1))]
        print ("RP IS A",type(RP))
        PC = RN+RP
        print ("PC IS A",type(PC))
    
    Reply
  8. Imagejemima john says

    June 6, 2019 at 10:02 pm

    So I tried this code with a much larger selection of data points. Somehow it won’t execute:
    PS: I’m not a statistician, so please be gently in your feedback. Thanks!

    import random
    #sampling with replacement
    list = [ 601, 602, 1001, 1201, 1801, 1802, 2201, 3501, 3502, 03601, 3801, 4101, 4102, 
    5701, 5702, 6801, 7901, 7902, 8601, 8602, 8701, 8702, 8901, 
    8902, 9001, 9002, 10601, 10602, 10701, 10702, 11201, 11202, 11301, 11302 ]
    sampling = random.sample(list, k=5)
    print("sampling with choices function ", sampling)
    
    Reply
    • ImageVishal says

      June 8, 2019 at 8:14 am

      Hi Jemina try this

      import random
      #sampling with replacement
      list = [601,602,1001,1201,1801,1802,2201,3501,3502,3601,
      3801,4101,4102,5701,5702,6801,7901,7902,8601,8602,8701,
      8702,8901,8902,9001,9002,10601,10602,10701,10702,11201,11202,
      11301,11302]
      sampling = random.sample(list, k=5)
      print("sampling with sample function", sampling)
      
      Reply
  9. Imagemasterdrew950 says

    April 27, 2019 at 3:36 am

    import numpy as np

    A1, A2, A3 is the column header
    0 to 4 is the index

    if we print out Array1 we get:

    A1, A2, A3
    0 [[ 2, 4, 6]
    1 [ 5, 10, 15]
    2 [ 6, 12, 18]
    3 [ 7, 14, 21]
    4 [ 8, 16, 24]]
    

    Know you want to randomly pick three numbers from Array1:
    using “random” or np.random

    out put1: 2, 10, 14
    “This tells you the location that the number is from” [A1,0], [A2,1], [A2,3]
    So the 2 is from column A1, row 0
    and the 10 is from column A2, row 1
    and 14 is from column A2,row3

    and if we run the code again, we get new random values
    out put2: 12, 10, 8 = [A2,2], [A3,2], [A1,4]

    Is it even possible pick n numbers from a 2D array and display the location they came from?

    Reply
  10. Imagemasterdrew950 says

    April 23, 2019 at 5:00 am

    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?

    Reply
    • ImageVishal says

      April 23, 2019 at 8:22 am

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

      Reply

Leave a Reply Cancel reply

your email address will NOT be published. all comments are moderated according to our comment policy.

Use <pre> tag for posting code. E.g. <pre> Your entire code </pre>

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 for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

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

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

Advertisement