Last updated: Feb 22, 2023
Reading timeยท3 min
The "ValueError: Sample larger than population or is negative" occurs when we
use the random.sample()
method to select more unique random elements than
there are values in the list.
To solve the error, use the random.choices()
method instead.
Here is an example of how the error occurs.
import random a_list = ['bobby', 'hadz', 'com'] # โ๏ธ ValueError: Sample larger than population or is negative random_elements = random.sample(a_list, 4)
The list only contains 3 elements, but we tried to select 4 random elements.
The random.sample() method returns a list of N unique elements chosen from the provided sequence.
One way to solve the error is to use the min()
function.
import random a_list = ['bobby', 'hadz', 'com'] random_elements = random.sample(a_list, min(4, len(a_list))) print(random_elements) # ๐๏ธ ['com', 'bobby', 'hadz']
The min function returns the smallest item in an iterable or the smallest of two or more arguments.
result = min(10, 5, 20) print(result) # ๐๏ธ 5
We used the function to return the list's length if N
exceeds the list's
length.
When using this approach at most len(list)
random element can be selected.
You can also use the random.choices()
method to solve the error.
import random a_list = ['bobby', 'hadz', 'com'] random_elements = random.choices(a_list, k=4) print(random_elements) # ๐๏ธ ['bobby', 'com', 'bobby', 'hadz']
The
random.choices()
method returns a k
sized list of elements chosen from the provided iterable
with replacement.
If the iterable is empty, the method raises an IndexError
exception.
On the other hand, the random.sample()
method is used for random sampling
without replacement.
If you need to get a single random element from a sequence, use the random.choice() method.
import random a_list = ['bobby', 'hadz', 'com'] random_element = random.choice(a_list) print(random_element) # ๐๏ธ hadz
The random.choice()
method returns a random element from a non-empty sequence.
If the provided sequence is empty, an IndexError
exception is raised.
If you need to handle a potential IndexError
exception, use a
try/except statement.
import random a_list = [] try: random_element = random.choice(a_list) print(random_element) # ๐๏ธ hadz except IndexError: print('The sequence is empty')
The list in the example is empty so an IndexError
is raised and is then
handled by the except
block.
You can learn more about the related topics by checking out the following tutorials: