Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does random.sample() method in python do?

Tags:

python

random

I want to know the use of random.sample() method and what does it give? When should it be used and some example usage.

like image 515
kartikeykant18 Avatar asked Mar 30 '14 07:03

kartikeykant18


People also ask

What is the purpose of a random sample?

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.

How do you select a random sample in Python?

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.

What is random sample in Python?

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.

What is the use of sample in Python?

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)

How to randomize a list 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.

How to pass a dictionary to random sample in Python?

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).


1 Answers

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). 
like image 136
alecxe Avatar answered Sep 25 '22 05:09

alecxe