I want to know the use of random.sample()
method and what does it give? When should it be used and some example usage.
Random sampling ensures that results obtained from your sample should approximate what would have been obtained if the entire population had been measured (Shadish et al., 2002). The simplest random sample allows all the units in the population to have an equal chance of being selected.
choice, sample, choices) In Python, you can randomly sample elements from a list with choice() , sample() , and choices() of the random module. These functions can also be applied to a string and tuple.
Python | random.sample() function. 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.
Last Updated : 29 Aug, 2018 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)
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.
Python random sample () function works with sequence, and the dictionary is not a sequence. If you try to pass the dictionary directly, you will get TypeError: Population must be a sequence or set. For dicts, use list (d).
According to documentation:
random.sample(population, k)
Return a k length list of unique elements chosen from the population sequence. Used for random sampling without replacement.
Basically, it picks k unique random elements, a sample, from a sequence:
>>> import random >>> c = list(range(0, 15)) >>> c [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] >>> random.sample(c, 5) [9, 2, 3, 14, 11]
random.sample
works also directly from a range:
>>> c = range(0, 15) >>> c range(0, 15) >>> random.sample(c, 5) [12, 3, 6, 14, 10]
In addition to sequences, random.sample
works with sets too:
>>> c = {1, 2, 4} >>> random.sample(c, 2) [4, 1]
However, random.sample
doesn't work with arbitrary iterators:
>>> c = [1, 3] >>> random.sample(iter(c), 5) TypeError: Population must be a sequence or set. For dicts, use list(d).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With