The Wayback Machine - https://web.archive.org/web/20240524235948/https://www.geeksforgeeks.org/python-random-sample-function/
Open In App

Python | random.sample() function

Last Updated : 29 Aug, 2018
Improve
Improve
Like Article
Like
Save
Share
Report

sample() is an inbuilt function of random module in Python that returns a particular length list of items chosen from the sequence i.e. list, tuple, string or set. Used for random sampling without replacement.

Syntax : random.sample(sequence, k)

Parameters:
sequence: Can be a list, tuple, string, or set.
k: An Integer value, it specify the length of a sample.

Returns: k length new list of elements chosen from the sequence.

Code #1: Simple implementation of sample() function.




# Python3 program to demonstrate
# the use of sample() function .
  
# import random 
from random import sample
  
# Prints list of random items of given length
list1 = [1, 2, 3, 4, 5] 
  
print(sample(list1,3))


Output:

[2, 3, 5]

 
Code #2: Basic use of sample() function.




# Python3 program to demonstrate
# the use of sample() function .
  
# import random 
import random
  
  
# Prints list of random items of
# length 3 from the given list.
list1 = [1, 2, 3, 4, 5, 6] 
print("With list:", random.sample(list1, 3))
  
# Prints list of random items of
# length 4 from the given string. 
string = "GeeksforGeeks"
print("With string:", random.sample(string, 4))
  
# Prints list of random items of
# length 4 from the given tuple.
tuple1 = ("ankit", "geeks", "computer", "science",
                   "portal", "scientist", "btech")
print("With tuple:", random.sample(tuple1, 4))
  
  
# Prints list of random items of
# length 3 from the given set.
set1 = {"a", "b", "c", "d", "e"}
print("With set:", random.sample(set1, 3))


Output:

With list: [3, 1, 2]
With string: ['e', 'f', 'G', 'G']
With tuple: ['ankit', 'portal', 'geeks', 'computer']
With set: ['b', 'd', 'c']

Note: Output will be different everytime as it returns a random item.
 
Code #3: Raise Exception

If the sample size i.e. k is larger than the sequence size, ValueError is raised.




# Python3 program to demonstrate the
# error of sample() function.
import random
  
list1 = [1, 2, 3, 4] 
   
# exception raised
print(random.sample(list1, 5)) 


Output:

Traceback (most recent call last):
  File "C:/Users/user/AppData/Local/Programs/Python/Python36/all_prgm/geeks_article/sample_method_article.py", line 8, in 
    print(random.sample(list1, 5))
  File "C:\Users\user\AppData\Local\Programs\Python\Python36\lib\random.py", line 317, in sample
    raise ValueError("Sample larger than population or is negative")
ValueError: Sample larger than population or is negative


Previous Article
Next Article

Similar Reads

Python Random - random() Function
There are certain situations that involve games or simulations which work on a non-deterministic approach. In these types of situations, random numbers are extensively used in the following applications: Creating pseudo-random numbers on Lottery scratch cardsreCAPTCHA on login forms uses a random number generator to define different numbers and ima
3 min read
Random sampling in numpy | sample() function
In Python numpy.random.sample() is one of the functionsgenerate that generates floating-point values in an open interval [0.0,1.0). It doesn't take up any arguments and produces a single random value each time it's called. This function is often used for statistical and simulation tasks in Python. Syntax : numpy.random.sample(size=None) Parameters:
2 min read
Random sampling in numpy | random() function
numpy.random.random() is one of the function for doing random sampling in numpy. It returns an array of specified shape and fills it with random floats in the half-open interval [0.0, 1.0). Syntax : numpy.random.random(size=None) Parameters : size : [int or tuple of ints, optional] Output shape. If the given shape is, e.g., (m, n, k), then m * n *
2 min read
Python - Random Sample Training and Test Data from dictionary
Sometimes, while working with Machine Learning Algorithm, we can have problem in which we need to differentiate the training and testing data randomly. This is very common problem and solution to it is desirable for Machine Learning domains. This article discusses approach to solve this without using external libraries. Method : Using keys() + rand
2 min read
PySpark Random Sample with Example
Are you in the field of job where you need to handle a lot of data on the daily basis? Then, you might have surely felt the need to extract a random sample from the data set. There are numerous ways to get rid of this problem. Don't know all the ways? Continue reading the article further to know more about the random sample extraction in the Pyspar
10 min read
NumPy random.noncentral_f() | Get Random Samples from noncentral F distribution
The NumPy random.noncentral_f() method returns the random samples from the noncentral F distribution. Example C/C++ Code import numpy as np import matplotlib.pyplot as plt gfg = np.random.noncentral_f(1.24, 21, 3, 1000) count, bins, ignored = plt.hist(gfg, 50, density = True) plt.show() Output: Syntax Syntax: numpy.random.noncentral_f(dfnum, dfden,
1 min read
Wand sample() function - Python
The sample() function is an inbuilt function in the Python Wand ImageMagick library which is used to change the image size by sampling the pixels. It’s quicker than resize() but less quality of image is provided. Syntax: sample(width, height) Parameters: This function accepts two parameters as mentioned above and defined below: width: This paramete
2 min read
random.vonmisesvariate() function in Python
random module is used to generate random numbers in Python. Not actually random, rather this is used to generate pseudo-random numbers. That implies that these randomly generated numbers can be determined. random.vonmisesvariate() vonmisesvariate() is an inbuilt method of the random module. It is used to return a random floating point number with v
2 min read
random.paretovariate() function in Python
random module is used to generate random numbers in Python. Not actually random, rather this is used to generate pseudo-random numbers. That implies that these randomly generated numbers can be determined. random.paretovariate() paretovariate() is an inbuilt method of the random module. It is used to return a random floating point number with Paret
2 min read
random.weibullvariate() function in Python
random module is used to generate random numbers in Python. Not actually random, rather this is used to generate pseudo-random numbers. That implies that these randomly generated numbers can be determined. random.weibullvariate() weibullvariate() is an inbuilt method of the random module. It is used to return a random floating point number with Wei
2 min read
Practice Tags :