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

Python | random.sample() function

Last Updated : 27 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

sample() is an built-in 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.

Python
# 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.

Python
# 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.

Python
# 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
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
random.normalvariate() 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.normalvariate() normalvariate() is an inbuilt method of the random module. It is used to return a random floating point number with norma
2 min read
random.gauss() 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.gauss() gauss() is an inbuilt method of the random module. It is used to return a random floating point number with gaussian distribution
2 min read
random.lognormvariate() 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.lognormvariate() lognormvariate() is an inbuilt method of the random module. It is used to return a random floating point number with log
2 min read
random.expovariate() 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.expovariate() expovariate() is an inbuilt method of the random module. It is used to return a random floating point number with exponenti
2 min read
random.shuffle() function in Python
The shuffle() is an inbuilt method of the random module. It is used to shuffle a sequence (list). Shuffling a list of objects means changing the position of the elements of the sequence using Python. Syntax of random.shuffle() The order of the items in a sequence, such as a list, is rearranged using the shuffle() method. This function modifies the
2 min read
random.gammavariate() 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.gammavariate() gammavariate() is an inbuilt method of the random module. It is used to return a random floating point number with gamma d
2 min read
Random sampling in numpy | ranf() function
numpy.random.ranf() 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.ranf(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 * k sa
2 min read
Random sampling in numpy | random_sample() function
numpy.random.random_sample() 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_sample(size=None) Parameters : size : [int or tuple of ints, optional] Output shape. If the given shape is, e.g., (m, n, k),
2 min read
Random sampling in numpy | random_integers() function
numpy.random.random_integers() is one of the function for doing random sampling in numpy. It returns an array of specified shape and fills it with random integers from low (inclusive) to high (exclusive), i.e. in the interval [low, high). Syntax : numpy.random.random_integers(low, high=None, size=None) Parameters : low : [int] Lowest (signed) integ
2 min read
Random sampling in numpy | randint() function
numpy.random.randint() is one of the function for doing random sampling in numpy. It returns an array of specified shape and fills it with random integers from low (inclusive) to high (exclusive), i.e. in the interval [low, high). Syntax : numpy.random.randint(low, high=None, size=None, dtype='l') Parameters : low : [int] Lowest (signed) integer to
2 min read
Python | Pandas Dataframe.sample()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas sample() is used to generate a sample random row or column from the function caller data frame. Syntax: DataFrame.sample(n=None,
2 min read
Python | Pandas Series.sample()
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index. Pandas Series.sample() function return a random sample of items from an axis of object. We ca
3 min read
3D Plotting sample Data from MongoDB Atlas Using Python
MongoDB, the most popular NoSQL database, is an open-source document-oriented database. The term ‘NoSQL’ means ‘non-relational’. It means that MongoDB isn’t based on the table-like relational database structure but provides an altogether different mechanism for storage and retrieval of data. This format of storage is called BSON ( similar to JSON f
3 min read
Python implementation of automatic Tic Tac Toe game using random number
Tic-tac-toe is a very popular game, so let's implement an automatic Tic-tac-toe game using Python. The game is automatically played by the program and hence, no user input is needed. Still, developing an automatic game will be lots of fun. Let's see how to do this. NumPy and random Python libraries are used to build this game. Instead of asking the
5 min read
Generating random Id's in Python
In python there are different ways to generate id's. Let's see how different types of Id's can be generated using python without using inbuilt Python libraries. 1. Generating Random Integer as Ids' Code #1 : Print 10 random values of numbers between 1 and 100. C/C++ Code # Python3 code to demonstrate the # random generation of Integer id's import r
2 min read
Generating Random id's using UUID in Python
We had discussed the ways to generate unique id's in Python without using any python inbuilt library in Generating random Id’s in Python In this article we would be using inbuilt functions to generate them. UUID, Universal Unique Identifier, is a python library which helps in generating random objects of 128 bits as ids. It provides the uniqueness
3 min read
uniform() method in Python Random module
uniform() is a method specified in the random library in Python 3. Nowadays, in general, day-day tasks, there's always the need to generate random numbers in a range. Normal programming constructs require a method more than just one word to achieve this particular task. In python, there's an inbuilt method, "uniform()" which performs this task with
2 min read
Python | Select random value from a list
Given a list and our task is to randomly select elements from the list in Python using various functions. Selecting random numbers from a list can be used sometimes while building games, choosing a random range, etc. Example Input: [2, 3, 4 , 5, 6 ] Output: 2 Explaination:The output we are getting is a random value from the input listSelect the Ran
5 min read
Python | Random Password Generator using Tkinter
With growing technology, everything has relied on data, and securing this data is the main concern. Passwords are meant to keep the data safe that we upload on the Internet. An easy password can be hacked easily and all personal information can be misused. In order to prevent such things and keep the data safe, it is necessary to keep our passwords
4 min read
SymPy | Permutation.random() in Python
Permutation.random() : random() is a sympy Python library function that returns the random permutation of length 'n'. Syntax : sympy.combinatorics.permutations.Permutation.random() Return : random permutation of length Code #1 : random() Example # Python code explaining # SymPy.Permutation.random() # importing SymPy libraries from sympy.combinatori
1 min read
Python - Get a sorted list of random integers with unique elements
Given lower and upper limits, generate a sorted list of random numbers with unique elements, starting from start to end. Examples: Input: num = 10, start = 100, end = 200 Output: [102, 118, 124, 131, 140, 148, 161, 166, 176, 180] Input: num = 5, start = 1, end = 100 Output: [37, 49, 64, 84, 95] To generate random numbers in Python, randint() functi
2 min read
Practice Tags :
three90RightbarBannerImg